如何在Python中使用ctypes加载DLL?

5
请提供一个示例,说明如何使用Python加载和调用c++ dll中的函数?
我发现一些文章说我们可以使用“ctypes”来使用Python加载和调用DLL中的函数。但是我无法找到一个可行的示例?
如果有人能提供一个示例,那就太好了。
1个回答

6

这是我在一个项目中使用的一些实际代码,用于加载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”的短名称会话。
另外两个参数只是长度和另一个字节,我现在不记得如何使用它(我应该更好地记录那段代码)。
步骤是:
- 加载DLL。 - 为函数设置原型和参数。 - 将其映射到Python名称(方便调用)。 - 创建必要的参数。 - 调用函数。
ctypes库具有所有C数据类型(int,char,short,void *等),并且可以通过值或引用传递参数。有一个教程位于这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接