Reading and writing C structs from Python

Thomas Heller thomas.heller at ion-tof.com
Wed Feb 13 13:17:48 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
>
> 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]".

This is exactly the kind of module (system?) I'm currently working on.
Your example would look like this:

>>> from ctypes import Structure, Array
>>> IntArray4 = Array(format="i", length=4)
>>> class PY_T(Structure):
...     _names_ = "x", "n"            # declare the field names
...     _formats_ = "f", IntArray4    # declare the field types
...
>>> py_t = PY_T() # creates an instance, there are other ways to create one if you already have a pointer to a C structure
<PY_T object read-write ptr 0x007F8078, size 20 at 0x00767D68>
>>> print py_t.x
0.0
>>> print py_t.n
<i_ARRAY_4 object read-write base 0x00767D68, ptr 0x007F807C, size 16 at 0x007F3BC8>
>>> print py_t.n[0]
0
>>> print py_t.n[3]
0
>>> print py_t.n[4]
Traceback (most recent call last):
  File "<stdin>", line 27, in ?
IndexError: invalid index

Still this needs some time to be finished...

Thomas





More information about the Python-list mailing list