Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that return a pointer to a struct with ctypes

Tags:

python

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.

like image 444
nowox Avatar asked Feb 24 '26 03:02

nowox


1 Answers

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

like image 170
Arpegius Avatar answered Feb 25 '26 17:02

Arpegius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!