简体   繁体   中英

ctypes - passing a struct with a pointer to another struct

In my C code I have:

typedef struct{
    int info1;
    int info2;
    MoreData* md;
} BasicData;

typedef struct{
    int extinfo[100];
    char stuff[100];
} MoreData;

Now I have a C library function which takes BasicData as argument and I want to call it from Python. To do this I construct a ctypes class:

class BasicData(Structure):
    _fields_ = [("info1", c_int),
                ("info2", c_int),
                ("md", ??????)]

My question is what do I fill into ???? space to be able to pass this struct to C function (or do I need something completely different?). MoreData is just used during computations and I don't need to read from it in my Python code so allocating memory for it will be handled from C library level. I just need to pass a BasicData struct with correct pointer type.

If you don't need to allocate or use the MoreData struct, then md is just a generic pointer as far as ctypes is concerned. Use a void * -- ie c_void_p .

You need to define a class MoreData(Structure) wrapping the other struct. Then pass that as ("md", POINTER(MoreData)) .

C guarantees that the struct fields are allocated in order, so if you really don't want to access md from Python then you can just not specify it in _fields_ (since it comes last). Then ctypes will believe that you have a struct with only the first two members.

Ctypes is fine for a one-off access to a C structure, but if you are routinely tying together C code with Python then I would really recommend you check out Cython.

Edit: As eryksun pointed out (feeble pun), I forgot the POINTER.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM