nowox
nowox

Reputation: 29066

Function that return a pointer to a struct with ctypes

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.

Upvotes: 3

Views: 3521

Answers (1)

Arpegius
Arpegius

Reputation: 5887

From documentation:

Pointer instances have a contents attribute 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

Upvotes: 9

Related Questions