林剑平 林剑平 - 1 month ago 19
C# Question

How can I package my python module and its dependencies such as Numpy/Scipy into one file like dll for C# calls?

In my project, some of the algorithms are implemented in python as Modules for calling and libraries such as Numpy/Scipy are used . Now I need to embed these Modules into my UI(implemented by C# and run in Windows 7). There are two reasons I need to package my python modules into a file like DLL(I don't want to package as an .exe because it is not friendly to embed). The first reason is for easily calling, and the second reason is to protect my algorithm source code. Does anyone have any idea?

Answer

Finally, I solve my problem by using nuitka. It compile my module into .pyd file, and I can import the module using pythonnet by adding reference Python.Runtime.dll. My compile command is:nuitka --module --nofreeze-stdlib --recurse-all --recurse-not-to=numpy --recurse-not-to=sklearn --recurse-not-to=pywt --recurse-not-to=matplotlib --recurse-not-to=matplotlib.pyplot --recurse-not-to=scipy.io myfile.py and my C# code is:

PythonEngine.Initialize();
IntPtr pythonLock = PythonEngine.AcquireLock();
PythonEngine.RunSimpleString("import sys\n");
PythonEngine.RunSimpleString("sys.path.append('C:\\path\\to\\pyd')\n");
PyObject pModule = PythonEngine.ImportModule("modulename");
pModule.InvokeMethod("funcitonname", para1, para2);
Comments