Using .PYD file in C#?

4.5k Views Asked by At

I am developing a program using C#, but I just figured out that what I am going to program is very very difficult in C# yet easy in Python. So what I want to do is make a .PYD file and use it in C# program, but I don't know how. I've been searching about it but I couldn't find anything.

So these are my questions: How do I use .PYD file in C#? I know that .PYD files are similar to .DLL files, so are .PYD files still usable in computers that have no Python installed?

2

There are 2 best solutions below

1
On

A .pyd file IS a DLL but with function init*() where * is the name of your .pyd file. For example, spam.pyd has a function named initspam(). They are not just similar, but the same! They are usable on PCs without Python.


Do not forget: builtins will NOT be available. Search for them in C, add them as an extern in your Cython code and compile!

0
On

Use pythonnet

Tutorial

You need a GIL state.

using (Py.GIL())
{
    // Your code here
}

Inside the GIL block, create a scope.

using (Py.GIL())
{
    using (PyScope scope = Py.CreateScope())
    {
        // Your code here
    }
}

To execute code:

scope.Exec(codeStr);

To set a variable:

scope.Set(name, value); // 'name' is a string and 'value' is a 'PyObject' object.

To convert to PyObject:

obj.ToPython()

Convert to PyObject if you need to put your object into Python.

To evaluate[0][1][2][3][4] an expression:

scope.Eval(expr)

To get a variable[5][6] value:

scope.Get(variableName)

C# code that doesn't have an end semicolon before any comment and is one-line represents an expression.

References

0: https://codereview.stackexchange.com/questions/160524/evaluating-arithmetic-expressions
1: https://www.programiz.com/python-programming/methods/built-in/eval
2: What does Python's eval() do? on SO
3: https://docs.python.org/3/reference/expressions.html
4: Python - Evaluate math expression within string on SO
5: https://realpython.com/python-variables
6: https://www.w3schools.com/python/python_variables.asp