Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python modules into DLL file

I am building a GUI using WPF on .NET Framework.I want to run python script (which uses modules like numpy, scipy ,etc) using C#. Now, I have two options.

  1. Process p = new Process(); //by passing necessary parameters like "python.exe" and "filename.py"
  2. Using IronPython

Using Method#1 is pretty much simpler but If I distribute this Application,then my End-User must have those python modules in the path specified by me in my Application. Using Method#2 I am facing problems with those python modules because they don't come with IronPython and I need DLL files of those modules. So is there any way to Convert Python Modules like numpy, scipy into DLL files?

like image 669
hemal7735 Avatar asked Sep 11 '15 18:09

hemal7735


People also ask

Can you make a DLL with Python?

Python embedding is supported in CFFI version 1.5, you can create a . dll file which can be used by a Windows C application. If you have a DllMain, you can declare it as "CFFI_DLLEXPORT int __stdcall DllMain(void* hinstDLL, unsigned long fdwReason, void* lpvReserved);" in your header file.

Where do I put Python DLL files?

In the vast majority of cases, the solution is to properly reinstall python. dll on your PC, to the Windows system folder. Alternatively, some programs, notably PC games, require that the DLL file is placed in the game/application installation folder.

How do I reference a DLL in Python?

Two steps are needed: Build the DLL using Visual Studio's compiler either from the command line or from the IDE; Link the DLL under Python using ctypes.


1 Answers

You can use clr.CompileModules to turn the python files into dll ones. You can add all the files into a single dll by doing something like this:

from System import IO
from System.IO.Path import Combine

def walk(folder):
  for file in IO.Directory.GetFiles(folder):
    yield file
  for folder in IO.Directory.GetDirectories(folder):
    for file in walk(folder): yield file

folder = IO.Path.GetDirectoryName(__file__)
all_files = list(walk(Combine(folder, 'moduleName')))

import clr
clr.CompileModules(Combine(folder, "myDll.dll"), *all_files)

You can then add a reference to your dll by doing something like this:

import clr
import sys

sys.path.append(r"C:\Path\To\Dll")
clr.AddReference("myDll.dll")

I don't however know how to access the functions inside that dll. According to this, you can import it by doing import moduleName. This does not work for me though.

Sources: [add files to single dll] [reference dll]

like image 175
Claudiu Avatar answered Nov 15 '22 01:11

Claudiu