C struct to Python

geremy condra debatem1 at gmail.com
Tue Nov 30 14:16:24 EST 2010


On Tue, Nov 30, 2010 at 10:57 AM, Eric Frederich
<eric.frederich at gmail.com> wrote:
> I am not sure how to proceed.
> I am writing a Python interface to a C library.
> The C library uses structures.
> I was looking at the struct module but struct.unpack only seems to
> deal with data that was packed using struct.pack or some other buffer.
> All I have is the struct itself, a pointer in C.
> Is there a way to unpack directly from a memory address?
>
> Right now on the C side of things I can create a buffer of the struct
> data like so...
>
>    MyStruct ms;
>    unsigned char buffer[sizeof(MyStruct) + 1];
>    memcpy(buffer, &ms, sizeof(MyStruct));
>    return Py_BuildValue("s#", buffer, sizeof(MyStruct));
>
> Then on the Python side I can unpack it using struct.unpack.
>
> I'm just wondering if I need to jump through these hoops of packing it
> on the C side or if I can do it directly from Python.
>
> Thanks,
> ~Eric

ctypes[0] sounds like a possible solution, although if you're already
writing a C extension it might be better practice to just write a
Python object that wraps your C struct appropriately. If you're not
wedded to the C extension, though, I've had very good luck writing C
interfaces with with ctypes and a few useful decorators [1], [2].
Others prefer Cython[3], which I like for speed but which sometimes
seems to get in my way when I'm trying to interface with existing
code. There's a good, if somewhat dated, overview of a few other
strategies here[4].

Geremy Condra

[0]: http://docs.python.org/library/ctypes.html
[1]: http://code.activestate.com/recipes/576734-c-struct-decorator/
[2]: http://code.activestate.com/recipes/576731/
[3]: http://www.cython.org/
[4]: http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html



More information about the Python-list mailing list