将对象传递给使用 ctypes 导入的 DLL 函数

Pass object to DLL function imported with ctypes

我需要在我的 python 应用程序中使用现有的库。 这是一个用于读取特定数据文件的库。 如果您好奇,可以从这里下载 https://www.hbm.com/en/2082/somat-download-archive/ (somat libsie)。

我需要做的第一件事就是打开文件,这样我的 python 脚本就会像这样开始:

import ctypes

hllDll = ctypes.WinDLL(r"libsie.dll")
context = hllDll.sie_context_new()
file = hllDll.sie_file_open(context, "test.sie".encode())

但我收到以下错误:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2019.3.5\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
OSError: exception: access violation reading 0x000000009F6C06B8

我确认 .sie 文件可以访问。 我认为问题在于作为第一个参数传递的“上下文”对象。我认为类型是问题。

这是定义上下文的头文件的一部分:

typedef void sie_Context;
...
SIE_DECLARE(sie_Context *) sie_context_new(void);
/* > Returns a new library context. */ 

我调用这些函数是否正确? 传递上下文对象有问题吗?

提前致谢

在 64 位系统上,return 值默认为 c_int(32 位)。至少,将 .restype 设置为至少 c_void_p 以指示 64 位指针是 returned。

理想情况下,为每个调用的函数设置 .argtypes.restype

import ctypes

hllDll = ctypes.WinDLL(r"libsie.dll")
hllDll.sie_context_new.argtypes = () # optional but recommended
hllDll.sie_context_new.restype = ctypes.c_void_p  # add this
hllDll.sie_context_new.argtypes = ctypes.c_void_p, ctypes.c_char_p # guess, need prototype
# hllDll.sie_context_new.restype = ???

context = hllDll.sie_context_new()
file = hllDll.sie_file_open(context, b"test.sie")