Reputation: 2594
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.
Upvotes: 2
Views: 917
Reputation: 1987
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.
Upvotes: 1
Reputation: 34270
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 *
-- i.e. c_void_p
.
Upvotes: 2