python ctypes将指向结构的指针作为参数发送给本机库 [英] python ctypes sending pointer to structure as parameter to native library

查看:134
本文介绍了python ctypes将指向结构的指针作为参数发送给本机库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将包装程序写入Linux中的本机库.问题是这样的:

I am trying to write a wrapper to a native library in Linux. Problem is this:

c中的定义:

definition in c:

int mymethod(mystruct* ptr)

在python中:

in python:

_lib.mymethod.argtypes = (ctypes.POINTER(mystruct),)
_lib.mymethod.restype = ctypes.c_int

_lib.mymethod.argtypes = (ctypes.POINTER(mystruct),)
_lib.mymethod.restype = ctypes.c_int

s = mystruct()

_lib.mymethod(ctypes.byref(s))
引发:预期的LP_mystruct实例,而不是指向mystruct的指针

_lib.mymethod(ctypes.byref(s))
raises: expected LP_mystruct instance instead of pointer to mystruct

_lib.mymethod(ctypes.pointer(s))
提高预期的LP_mystruct实例而不是LP_mystruct

_lib.mymethod(ctypes.pointer(s))
raises expected LP_mystruct instance instead of LP_mystruct

错误.如何将结构作为指针传递给本机方法?

errors. How to pass a structure as a pointer to a native method ?

谢谢.

遇见

推荐答案

问题在于,在Python中,来自ctypes的更高级别的"POINTER"与通用指针"(ctypes.CArgObject)(返回的值)或代表内存地址的单个数字(这是ctype的adrresof返回的值)-您可以注释函数以接收`ctypes.c_voidp并用_lib.mymethod(ctypes.addressof(a))调用它-

The problem is that the higher level "POINTER" from ctypes is, in Python, a different object than "a generic pointer" (ctypes.CArgObject by ctypes.byref)which is returned or a single number representing a memory address (which is what is returned by ctype's adrresof) - you can either annotate your function to receive a `ctypes.c_voidp and call it with _lib.mymethod(ctypes.addressof(a)) instead -

或者如果您想在强类型化方面工作,以避免会导致Python崩溃的错误(类型错误会引发Python异常-传递给函数的错误参数会导致Python解释器本身发生分段错误),您必须创建一个变量来保存新的类型",它是结构的POINTER-然后使用结构的地址创建该类型的实例:

Or if you want to work on the stronged-typed side to avoid errors that would crash Python (a type error raises a Python exception instead - a wrong parameter passed to a C unction would cause a segmentation fault on the Python interpreter itself), you have to create a variable to hold the new "type" which is a POINTER to your structure - and then create an instance of this type with the address of your structure:

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将指向结构的指针作为参数发送给本机库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆