[英]How to load DLL using ctypes in Python?
请提供一个示例,说明如何使用Python加载和调用c ++ 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。 这个特定的终端模拟器允许短名称会话“A”到“Z”。
另外两个参数只是一个长度和另一个字节,其使用目前逃避了我(我应该记录该代码更好)。
步骤是:
ctypes库具有所有C数据类型( int
, char
, short
, void*
等),并且可以通过值或引用传递参数。 还有位于教程这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.