gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:58:04 26 4
gpt4 key购买 nike

请提供一个示例,解释如何使用 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”)是 session ID。这个特定的终端仿真器允许“A”到“Z”的短名称 session 。

其他两个参数只是一个长度和另一个字节,目前我无法使用它们(我应该更好地记录该代码)。

步骤是:

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

ctypes 库具有所有 C 数据类型(intcharshortvoid* 和依此类推),并且可以按值或引用传递参数。有一个教程位于 here .

关于python - 如何在 Python 中使用 ctypes 加载 DLL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1781531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com