MaXim
MaXim

Reputation: 63

Trouble with passing struct to native library with ctypes

I'm having a little trouble with using ctypes for the first time in Python 2.7. The issue is as follows:

  1. I call a function in the native code to give me some memory. The function gives me a pointer to the buffer. The buffer is cast to a ctypes struct before proceeding.
  2. I assign some struct members and also perform a memmove to fill the fields I need to.
  3. A pointer to the buffer is passed to another function in the library.

The issue is that the other function is not seeing any of the changes that I made while in Python. I confirmed this using gdb on the Python interpreter. Basically, none of the operations that I performed appeared to have any effect, and the fields I expected to be set were zero or contained no data.

Here is the Python code that interacts with the library:

pxCspPacket = ctypes.cast(                                  
        pycsp.csp_buffer_get(bytesToSend),          
        ctypes.POINTER(pycsp.csp_packet_t))

pxCspPacket.contents.length = bytesToSend
ctypes.memmove(pxCspPacket.contents.data,                   
        dataToSend,                                         
        bytesToSend)

# Send packet
pycsp.csp_send(conn, pxCspPacket, self.cspTimeout)

The bindings to the library are as follows:

class csp_packet_t (ctypes.Structure):
        _pack_ = 1
        _fields_ = [("padding", ctypes.c_uint8 * 46),
            ("length", ctypes.c_uint16),
            ("id", csp_id_t),
            ("data", ctypes.c_uint8 * 256)]

The corresponding definition for the struct in C:

typedef struct __attribute__((__packed__)) {
        uint8_t padding[CSP_PADDING_BYTES]; 
        uint16_t length;
        csp_id_t id;
        union {
                uint8_t data[0];
                uint16_t data16[0];
                uint32_t data32[0];
        };
} csp_packet_t;

Thanks in advance for any help!

Upvotes: 0

Views: 374

Answers (1)

MaXim
MaXim

Reputation: 63

I discovered the issue, and it wasn't to do with the way I was using ctypes. It turns out that the definition for the struct in C differed from my python binding - CSP_PADDING_BYTES was defined to be 8 bytes in the native library, while the padding in the Python binding is set to 46 bytes.

The binding and struct definition isn't my own code, but at least I know how to fix it!

Upvotes: 1

Related Questions