2011-03-09 94 views
13

如何將一個winDLL導入python並能夠使用它的所有功能?它只需要雙打和字符串。Python導入dll

+0

你有什麼,到目前爲止,怎麼不工作? – 2011-03-10 00:01:02

+0

與這個問題重複嗎? http://stackoverflow.com/questions/252417/how-can-i-use-a-dll-from-python – payne 2011-03-10 00:01:34

回答

13

你已經標記了問題ctypes,所以它聽起來像你已經知道答案。

ctypes tutorial非常好。一旦你閱讀並理解你可以輕鬆完成。

例如:

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

而且從我自己的代碼示例:

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

那麼,我知道我需要ctypes,但我不知道如何使用它們。 :) 另外,非常好的鏈接! python文檔似乎只適合參考,但不是真正的學習。萬分感謝! – pajm 2011-03-10 00:09:09

+0

等一下!我想我忽略了你的代碼。看了教程後,它似乎只演示如何加載Windows DLL。我需要加載一個自定義的DLL文件。我將如何做到這一點? – pajm 2011-03-10 02:50:03

+0

@Patrick我又增加了一個例子。但是這些都在教程中。調用你自己的DLL和Windows DLL沒有任何理論上的區別。 – 2011-03-10 07:51:52

2

使用Cython,既可以訪問DLL,也可以爲它們生成Python綁定。

3

我張貼我的經驗。首先,儘管我把所有的東西都拼湊在一起,但是導入C#dll很簡單。我所採取的方式是:

1)安裝本NuGet包(我不是老闆,只是非常有用),以建立一個非託管的DLL:https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

2)你的C#DLL的代碼是這樣這樣的:

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)你的Python代碼是這樣的:

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"))