ctypes - pointer to array of structs?

Thomas Heller theller at ctypes.org
Fri Jan 4 14:09:24 CET 2008


skip at pobox.com schrieb:
> (Is this the right place to ask ctypes questions?  There's a mailing list
> but the last post to it seems to have been in November 2006.)

You could use the ctypes-users mailing list:
https://lists.sourceforge.net/lists/listinfo/ctypes-users

It is also available via gmane.

> Using ctypes I reference a structure which contains a pointer to an array of
> another structure:
> 
>     class SYMBOL(Structure):
>         _fields_ = [("symbol", c_char_p),
>                     ("num", c_int),
>                     ("units", c_int),
>                     ("baseprice", c_int),
>                     ("active", c_int)]
>     SYMBOL_PTR = POINTER(SYMBOL)
> 
>     class TABLE(Structure):
>         _fields_ = [("map", SYMBOL_PTR),
>                     ("nsymbols", c_uint),
>                     ...]
> 
> Effectively, TABLE.map is an array of TABLE.nsymbols SYMBOLS.  How to I
> reference elements in that array?  In C I would just treat TABLE.map like an
> array and index into it (for i=0; i< TABLE.nsymbols; i++) ...).  This is
> data returned from a C library, not something I'm building in Python to pass
> into C.

Assuming you got a pointer to TABLE from a function call like this:

  somefunction.restype = POINTER(TABLE)

  ptab = somefunction(...)

then you should be able to use this code (C has the '*' operator
to derefence pointers, Python does not so you have to use p[0] instead
of *p):

  table = ptab[0]
  symp = table.map
  for i in range(table.nsymbols):
    sym = symp[0]
    print sym.symbol, sym.num, sym.units, sym.baseprice

Thomas




More information about the Python-list mailing list