我正在尝试为 Linux 中的 native 库编写一个包装器。问题是这样的:
定义在c:
int mymethod(mystruct* ptr)
在 python 中:
_lib.mymethod.argtypes = (ctypes.POINTER(mystruct),)
_lib.mymethod.restype = ctypes.c_int
s = mystruct()
_lib.mymethod(ctypes.byref(s))
# raises: expected LP_mystruct instance instead of pointer to mystruct
_lib.mymethod(ctypes.pointer(s))
# raises expected LP_mystruct instance instead of LP_mystruct
错误。如何将结构作为指向 native 方法的指针传递?
谢谢。
测量
最佳答案
问题在于,在 Python 中,来自 ctypes 的更高级别的“POINTER”是一个不同于“通用指针”的对象(ctypes.CArgObject
by ctypes.byref
) 返回或表示内存地址的单个数字(这是 ctype 的 adrresof
返回的内容) - 您可以注释您的函数以接收 `ctypes.c_voidp
并用 _lib.mymethod(ctypes.addressof(a))
调用它 -
或者如果你想在强类型方面工作以避免会导致 Python 崩溃的错误(类型错误反而会引发 Python 异常 - 传递给 C 函数的错误参数会导致 Python 解释器本身出现段错误),你必须创建一个变量来保存新的“类型”,它是指向你的结构的指针——然后用你的结构的地址创建一个这种类型的实例:
mystruct_pointer = ctypes.POINTER(mystruct)
_lib.mymethod.argtypes = (mystruct_pointer,)
_lib.mymethod.restype = ctypes.c_int
s = mystruct()
_lib.mymethod(mystruct_pointer.from_address(ctypes.addressof(s)))
关于python ctypes将指向结构的指针作为参数发送给 native 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9126031/