Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a pointer to a structure in ctypes?

I try to pass a pointer of a structure which is given me as a return value from the function 'bar' to the function 'foo_write'. But I get the error message 'TypeError: must be a ctypes type' for line 'foo = POINTER(temp_foo)'. In the ctypes online help I found that 'ctypes.POINTER' only works with ctypes types. Do you know of another way? What would you recommend?

C:

typedef struct FOO_{
    int i;
    float *b1;
    float (*w1)[];
}FOO;

foo *bar(int foo_parameter) {...
void foo_write(FOO *foo)

Python with ctypes:

class foo(Structure):
    _fields_=[("i",c_int),
              ("b1",POINTER(c_int)),
              ("w1",POINTER(c_float))]

temp_foo=foo(0,None,None)
foo = POINTER(temp_foo)
foo=myclib.bar(foo_parameter)
myclib.foo_write(foo)
like image 516
Framester Avatar asked Jun 28 '10 11:06

Framester


People also ask

What does Ctypes CDLL do?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

What is C_char_p?

c_char_p is a subclass of _SimpleCData , with _type_ == 'z' . The __init__ method calls the type's setfunc , which for simple type 'z' is z_set . In Python 2, the z_set function (2.7. 7) is written to handle both str and unicode strings.


1 Answers

Change

foo = POINTER(temp_foo)

to

foo = pointer(temp_foo)

can solve the problem.

Please see http://docs.python.org/library/ctypes.html#ctypes-pointers for more information.

like image 93
czchen Avatar answered Sep 21 '22 15:09

czchen