我的C函数原型(prototype)是:
typedef struct {
int a;
int b;
} foo_t;
foo_t* foo(int a);
在 Python 中我必须重新定义我的结构:
class Foo(Structure):
_fields_ = [("a", c_int), ("b", c_int)]
我的问题是如何在 Foo
中正确地转换我的返回值?
>>> dll.foo.restype = POINTER(Foo)
>>> ret = dll.foo(42);
>>> print ret
<dll.LP_Foo object at 0xffe7c98c>
>>> print ret.a
AttributeError: 'LP_Foo' object has no attribute 'a'
我也尝试过 Foo
而不是 POINTER(Foo)
。有了这个,我可以访问 Foo
成员,但值是错误的。
来自 ctypes我可以读到这个:
ctypes.POINTER(type) This factory function creates and returns a new ctypes pointer type. Pointer types are cached an reused internally, so calling this function repeatedly is cheap. type must be a ctypes type
所以类型不能是Foo
。我可能必须找到另一种方法。
最佳答案
来自文档:
Pointer instances have a
contents
attribute which returns the object to which the pointer points
所以尝试:
>>> print ret.contents.a
请注意文档说明:
Note that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute
关于python - 返回指向具有 ctypes 的结构的指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370917/