ctypes: nested structures and pointers


Gabriele Modena

Hi all,
I am trying to learn ctypes and I am facing some problems In wrapping
two nested structs.

<--- begin C code ---->
struct dev_callbacks; // Prototype the callback struct

typedef struct {
const struct dev_callbacks* pdc;
chip_type ct;
dev_spec ds;
bool bActive;
bool bCrc;
bool bPar;
uint8_t ui8TxBits;
} dev_info;

struct dev_callbacks {
const char* acDriver;
dev_info* (*connect)(const uint32_t uiIndex);
bool (*transceive)(const dev_spec ds, const byte_t* pbtTx, const
uint32_t uiTxLen, byte_t* pbtRx, uint32_t* puiRxLen);
void (*disconnect)(dev_info* pdi);

<---- End C code ---->

I have two problems with this code:

1. what is the correct (pythonic) way to capture the prototype
definition of dev_callbacks and the relation between that structure
and dev_info?

2. is it correct to wrap "connect", "transceive" and "disconnect" in
separate structures and reference them within pyDEV_CALLBACKS?

The (stub) code I wrote for now looks like this:

class pyDEV_CALLBACKS(Structure):
_fields_ = [("acDriver", c_char_p), ("connect", c_void_p),
("transceive", c_bool), ("disconnect", c_void_p) ]

class pyDEV_INFO(Structure):
_fields_ = [ ("pdc", POINTER(pyDEV_CALLBACKS)), ("ct", c_ubyte),
("ds", c_void_p), ("acName", c_char * 256), ("bActive",
c_bool), ("bCrc", c_bool), ("bPar", c_bool), ("ui8TxBits", c_ubyte) ]

Passing the data structures to wrapper functions seem to work (the
data is initialized), but the result is not what expected (I presume
the problems are related to memory alignment due to wrong


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question