The prototype of my C function is:
typedef struct {
int a;
int b;
} foo_t;
foo_t* foo(int a);
In Python I have to redefine my structure:
class Foo(Structure):
_fields_ = [("a", c_int), ("b", c_int)]
My question is how do I properly cast my return value in 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'
I have also tried Foo instead of POINTER(Foo). With this I can access Foo members but the values are wrong.
From ctypes I can read this:
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
So type cannot be Foo. I probably have to find another way.
From documentation:
Pointer instances have a
contentsattribute which returns the object to which the pointer points
So try:
>>> print ret.contents.a
Be aware that the documentation states:
Note that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With