Reading and writing C structs from Python

John Machin sjmachin at lexicon.net
Tue Feb 12 21:10:44 EST 2002


"Edward C. Jones" <edcjones at erols.com> wrote in message news:<3C696FC7.1090600 at erols.com>...
> Suppose I have a C struct for example

Initial reaction is to say "Don't do that". There is no answer that is
both helpful and easy. Trying to establish how many degrees of freedom
you have:
Are you wrapping *existing* C code as a Python extension? 
Are you planning to write some C code whose sole purpose is to be
called from Python as an extension?
Are you embedding Python in an existing application?
Who will use it? (You / colleagues / universe)
Multi-platform ? E.g. is the interface meant to work for all
reasonable values of sizeof(int)?
One-off throw-away or critical 24x7 app?

> 
> typedef struct {
> float x;

float or double?

> int n[4];
> } test;
> 
> and a pointer to an instance of the struct
> 
> test* t = (test*) malloc(sizeof(test));

If possible, use PyMem_Malloc() and friends.

> 
> I would like to wrap this in a python object "py_t" so that (in Python) 
> "x = py_t.x" reads "t.x" and "py_t.x = 13.0" writes to "t.x".

Do you mean not "t.x" but "t->x"?

> Ditto for "py_t.n[i]".

So n is to be interpreted by the Python side as a list, not a tuple,
one gathers. What would you like to happen if the Python side does:

py_t.n[0] = x where x is not an int

py_t.n.append(any_object)

py_t.n.extend(some_list)

etc etc

Is it possible that you can regard your struct as logically an
instance of a class and in OO fashion provide methods to do whatever
the object should do, rather than letting the Python side peek and
poke at the attributes?

> Ideally I would like to do this using a C function 
> something like:
> 
> PyObject* PyObject_FromCStruct(void* t, char* format)
> void* PyObject_AsCStruct(PyObject* pyo, char* format)
> 
> The format strings used in module "struct" would be fine.

Yes, but if you really need to handle arrays, you would need to
introduce brackets, so that you can describe your example struct as
"f[iiii]".

> 
> My guess is that this is a job for

I guess otherwise.

> the notoriously confusing "buffer interface".

Ha! Common ground at last :-)

> Does anyone have any sample code for problems like this?

If you really want to do the to/from struct thing, then perusal of the
source of (a) the struct module (b)PyArg_ParseTuple() and
Py_BuildValue() might be a good start.



More information about the Python-list mailing list