How to return a pointer to a structure in ctypes?

23,969

Solution 1

Your bar function has an incorrect definition, I guess you mean it is struct FOO_ *bar(int);?

The Python code is wrong in the sense that foo_parameter is never declared, so I'm not 100% sure what you want to do. I assume you want to pass a parameter of your python-declared foo, which is an instance of a struct FOO_, into the C bar(int) and get back a pointer to struct FOO_.

You don't need POINTER to do that, the following will work:

#!/usr/bin/env python
from ctypes import *

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

myclib = cdll.LoadLibrary("./libexample.so")
temp_foo = foo(1,None,None)
foovar = myclib.bar(temp_foo.i)
myclib.foo_write(foovar)

Since CTypes will wrap the return type of bar() in a pointer-to-struct for you.

Solution 2

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.

Share:
23,969
Framester
Author by

Framester

Updated on January 20, 2020

Comments

  • Framester
    Framester over 4 years

    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)
    
  • Framester
    Framester almost 14 years
    Hi rq, i chose you as you pointed out, that I don't need ctypes.POINTER at all.
  • fadedbee
    fadedbee over 11 years
    Is foo a classname, or a variable here? How does c_types know that the return type of bar is 'foo'?
  • Overdrivr
    Overdrivr over 8 years
    foo is both a class and a variable name ?
  • Ben Moss
    Ben Moss over 8 years
    FWIW the above 2 comments about class vs variable name are obsolete after the last edit.