在Python中使用DLL文件的最简单方法是什么?
具体来说,如何在不编写任何额外的包装器c++代码将功能公开给Python的情况下实现这一点呢?
本机Python功能比使用第三方库更受欢迎。
在Python中使用DLL文件的最简单方法是什么?
具体来说,如何在不编写任何额外的包装器c++代码将功能公开给Python的情况下实现这一点呢?
本机Python功能比使用第三方库更受欢迎。
当前回答
ctypes将是最容易使用的东西,但(错误地)使用它会使Python崩溃。如果你试图快速做某事,而且你很小心,这很好。
我鼓励你去看看Boost Python。是的,它要求你写一些c++代码,并有一个c++编译器,但你实际上不需要学习c++来使用它,你可以从微软得到一个免费的(就像啤酒一样)c++编译器。
其他回答
本页有一个从DLL文件调用函数的非常简单的示例。
为了完整起见,在这里解释一下细节:
It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: add and sub which take two arguments. add(a, b) returns addition of two numbers sub(a, b) returns substraction of two numbers The name of the DLL file will be "demo.dll" Program: from ctypes import* # give location of dll mydll = cdll.LoadLibrary("C:\\demo.dll") result1= mydll.add(10,1) result2= mydll.sub(10,1) print("Addition value:"+result1) print("Substraction:"+result2) Output: Addition value:11 Substraction:9
c类型可以用来访问dll,这里有一个教程:
http://docs.python.org/library/ctypes.html#module-ctypes
如果DLL是COM库类型,则可以使用pythonnet。
pip install pythonnet
然后在python代码中,尝试以下操作
import clr
clr.AddReference('path_to_your_dll')
# import the namespace and class
from Namespace import Class
# create an object of the class
obj = Class()
# access functions return type using object
value = obj.Function(<arguments>)
然后根据DLL中的类实例化一个对象,并访问其中的方法。
也许与调度:
from win32com.client import Dispatch
zk = Dispatch("zkemkeeper.ZKEM")
其中zkemkeeper是在系统上注册的DLL文件… 之后,你可以通过调用函数来访问它们:
zk.Connect_Net(IP_address, port)
ctypes将是最容易使用的东西,但(错误地)使用它会使Python崩溃。如果你试图快速做某事,而且你很小心,这很好。
我鼓励你去看看Boost Python。是的,它要求你写一些c++代码,并有一个c++编译器,但你实际上不需要学习c++来使用它,你可以从微软得到一个免费的(就像啤酒一样)c++编译器。