C struct to Python

Eric Frederich eric.frederich at gmail.com
Tue Nov 30 13:57:56 EST 2010


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



More information about the Python-list mailing list