Reading and writing C structs from Python

Michael Hudson mwh at python.net
Wed Feb 13 08:21:54 EST 2002


"Edward C. Jones" <edcjones at erols.com> writes:

> Suppose I have a C struct for example
> 
> typedef struct {
> float x;
> int n[4];
> } test;
> 
> and a pointer to an instance of the struct
> 
> test* t = (test*) malloc(sizeof(test));
> 
> 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". Ditto for "py_t.n[i]". Ideally I would like to do this using a
> C function something like:

You know about the functions in Python/structmember?  Used by, e.g.,
complex objects:

static PyMemberDef complex_members[] = {
        {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
         "the real part of a complex number"},
        {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
         "the imaginary part of a complex number"},
        {0},
};

you can stick this in the tp_members slot of the type object or do
your work in your tp_getattro function.

OTOH, this doesn't really handle things like "int n[4]".

> PyObject* PyObject_FromCStruct(void* t, char* format)

What type would the returned object have?

> void* PyObject_AsCStruct(PyObject* pyo, char* format)

How would this know how to get the data out of the PyObject?

> The format strings used in module "struct" would be fine.

I think you need to supply more info than that (like field names!).

> My guess is that this is a job for the notoriously confusing "buffer
> interface". 

I doubt it.

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

Well, when confronted with this kind of problem, I've generally coded
it by hand.  Not much fun, but it doesn't really require many
braincells.

Cheers,
M.

-- 
42. You can measure a programmer's perspective by noting his
    attitude on the continuing vitality of FORTRAN.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html



More information about the Python-list mailing list