4
请给我一个例子,解释如何加载&使用Python在C++ dll中调用函数?如何在Python中使用ctypes加载DLL?
我发现一些文章说我们可以使用“ctypes”来使用Python加载和调用DLL中的函数。但我无法找到工作样本?
如果有人向我提供如何做到这一点,这将是一件好事。
请给我一个例子,解释如何加载&使用Python在C++ dll中调用函数?如何在Python中使用ctypes加载DLL?
我发现一些文章说我们可以使用“ctypes”来使用Python加载和调用DLL中的函数。但我无法找到工作样本?
如果有人向我提供如何做到这一点,这将是一件好事。
这里是一些实际代码我用在一个项目中加载一个DLL,查找一个函数,并设置和调用该函数。
import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")
# Set up prototype and parameters for the desired function call
# in the DLL, `HLLAPI()` (the high-level language API). This
# particular function returns an `int` and takes four `void *`
# arguments.
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p)
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0)
# Actually map the DLL function to a Python name `hllApi`.
hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)
# This is how you can actually call the DLL function. Set up the
# variables to pass in, then call the Python name with them.
p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p ("Z")
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
在这种情况下的功能是一个在终端模拟器包,这是一个非常简单的一个 - 它采取四个参数和返回值不(一些经由指针参数实际上返回)。第一个参数(1)表示我们要连接到主机。
第二个参数(“Z”)是会话ID。这个特定的终端模拟器允许通过“Z”的短名称的“A”。
另外两个参数只是一个长度,另一个字节的使用目前使我摆脱了困境(我应该记录下代码更好一点)。
的步骤是于:
的ctypes的库具有的所有C数据类型(int
,char
,short
,void*
等),并且可以通过数值或引用传递参数。有一个教程位于here。