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

Mad*_*ras 5 python

请提供一个示例,说明如何使用Python加载和调用c ++ dll中的函数?

我发现一些文章说我们可以使用"ctypes"来加载并使用Python调用DLL中的函数.但我无法找到工作样本?

如果有人向我提供如何做的样本会很棒.

pax*_*blo 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))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,函数是终端仿真器包中的一个,它是一个非常简单的函数 - 它需要四个参数并且没有返回任何值(一些实际上是通过指针参数返回的).第一个参数(1)表示我们要连​​接到主机.

第二个参数("Z")是会话ID.这个特定的终端模拟器允许短名称会话"A"到"Z".

另外两个参数只是一个长度和另一个字节,其使用目前逃避了我(我应该记录该代码更好).

步骤是:

  • 加载DLL.
  • 设置函数的原型和参数.
  • 将其映射到Python名称(以便于调用).
  • 创建必要的参数.
  • 调用该函数.

该ctypes的库具有的所有C数据类型(int,char,short,void*等等),并且可以通过数值或引用传递参数.还有位于教程这里.