C struct to Python

Discussion in 'Python' started by Eric Frederich, Nov 30, 2010.

  1. 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
    Eric Frederich, Nov 30, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. RA Scheltema
    Replies:
    3
    Views:
    380
    RA Scheltema
    Jan 6, 2004
  2. Gunnar G

    struct in struct

    Gunnar G, May 31, 2004, in forum: C++
    Replies:
    14
    Views:
    784
  3. DanielEKFA
    Replies:
    8
    Views:
    584
    DanielEKFA
    May 16, 2005
  4. James Harris
    Replies:
    4
    Views:
    1,355
    James Harris
    Oct 9, 2003
  5. Chris Fogelklou
    Replies:
    36
    Views:
    1,345
    Chris Fogelklou
    Apr 20, 2004
Loading...

Share This Page