ctypes: nested structures and pointers

Gabriele Modena gabriele.modena at gmail.com
Mon Jan 18 10:33:44 CET 2010


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;
  char acName[DEVICE_NAME_LENGTH];
  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
declarations),

-- 
Gabriele



More information about the Python-list mailing list