python ctypes将指向结构的指针作为参数发送给 native 库

标签 python pointers struct ctypes

我正在尝试为 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/

相关文章:

python - 如何从 Python 函数调用中捕获标准输出输出?

python - 如何使用注意力机制在多层双向中操纵编码器状态

c++ - 结构给出不正确的输出

c++ - 如何使用指针通过函数传递对象?

c++ - 具有位字段重新排序的结构?

c++ - 如何初始化具有 const 变量的结构数组

python - 需要此正则表达式的帮助

python - 当使用python更新文档时,Elasticsearch抛出异常 `index_failed_engine_exception`

c - 指向包含指针的结构的指针

c - 段错误释放内存 - 仅当分配的内存太多时