How do I pass structures using a C extension?

Diez B. Roggisch deetsNOSPAM at web.de
Mon Mar 14 08:44:24 EST 2005


timothy.williams at nvl.army.mil wrote:

> Hi.
> 
> I trying to write an extension module to call some C libraries so I can
> use them in Python. Several of the library functions pass pointers to
> structures as arguments. I was thinking that I could create a class for
> each structure, but I'm not sure how to get the data back and forth.
> The example the "Extending and Embedding the Python Interpreter" manual
> has examples of passing strings and ints using
> PyArg_ParseTupleAndKeywords(), but it's not clear to me if I can even
> pass structs around like this.
> 
> I'm just learning how to do extensions, so any help is greatly
> appreciated.

There are several ways you can accomplish this. You could use the module
"struct" to create byte-string representations of your structs and pass
these to your extension. In C, you just cast the string-pointer to your
struct and pass it. Disadvantages are: low security, and cumbersome on the
python side. Another way would be to pass the structures as python
structures - tuples and/or lists. Then manually disassemble these is the
extension (PyArg_ParseTupleAndKeywords and co. help you a great deal here)
and create an instance of the desired struct. A third way could be to
create an extension type that resembles your struct and use that to create
the "real" struct by getting the types instance values.

HTH
-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list