2011-03-09 29 views
13

¿Cómo importaría un winDLL a python y podría usar todas sus funciones? Solo necesita dobles y cadenas.Python importar dll

+0

¿Qué tienes hasta el momento, y cómo no funciona? –

+0

¿Duplicar con esta pregunta? http://stackoverflow.com/questions/252417/how-can-i-use-a-dll-from-python – payne

Respuesta

13

Has etiquetado la pregunta ctypes y parece que ya sabes la respuesta.

El ctypes tutorial es excelente. Una vez que haya leído y entendido que podrá hacerlo fácilmente.

Por ejemplo:

>>> from ctypes import * 
>>> windll.kernel32.GetModuleHandleW(0) 
486539264 

Y un ejemplo de mi propio código:

lib = ctypes.WinDLL('mylibrary.dll') 
#lib = ctypes.WinDLL('full/path/to/mylibrary.dll') 
func = lib['myFunc']#my func is double myFunc(double); 
func.restype = ctypes.c_double 
value = func(ctypes.c_double(42.0)) 
+0

Bueno, sabía que necesitaba ctypes pero no sabía cómo usarlos. :) ¡También, muy buen enlace! La documentación de Python parece ser solo una buena referencia, pero no un aprendizaje real. ¡Gracias una tonelada! – pajm

+0

¡Espera! Creo que pasé por alto tu código. Después de mirar el tutorial, parece que solo demuestra cómo cargar archivos DLL de Windows. Necesito cargar un archivo DLL personalizado. ¿Cómo haría esto? – pajm

+0

@Patrick He agregado otro ejemplo. Pero todo está allí en el tutorial. No hay diferencia teórica entre llamar a su propia DLL y una DLL de Windows. –

2

Use Cython, ambos para acceder a las DLL y generar enlaces de Python para ellas.

3

Quiero poner mi experiencia. En primer lugar, a pesar de todo el arduo trabajo que me llevó a juntar todas las piezas, importar un dll C# es fácil. La forma en que lo hice es:

1) instala este paquete Nuget (no soy propietario, es simplemente muy útil) con el fin de construir un archivo DLL no administrado: https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

2) Su código C# DLL es igual esto:

using System; 
using RGiesecke.DllExport; 
using System.Runtime.InteropServices; 

public class MyClassName 
{ 
    [DllExport("MyFunctionName",CallingConvention = CallingConvention.Cdecl)] 
    [return: MarshalAs(UnmanagedType.LPWStr)] 
    public static string MyFunctionName([MarshalAs(UnmanagedType.LPWStr)] string iString) 
    { 
     return "hello world i'm " + iString 
    } 
} 

3) Su código Python es así:

import ctypes 
#Here you load the dll into python 
MyDllObject = ctypes.cdll.LoadLibrary("C:\\My\\Path\\To\\MyDLL.dll") 
#it's important to assing the function to an object 
MyFunctionObject = MyDllObject.MyFunctionName 
#define the types that your C# function return 
MyFunctionObject.restype = ctypes.c_wchar_p 
#define the types that your C# function will use as arguments 
MyFunctionObject.argtypes = [ctypes.c_wchar_p] 
#That's it now you can test it 
print(MyFunctionObject("Python Message"))