简体   繁体   中英

Python Ctypes 'create_string_buffer' as char pointer byte array

I have a function whose argument is a char pointer which is used as a buffer to store some byte message:

struct test {
    unsigned char *buffer;
    uint32_t bufferSize;
    uint32_t bufferEnd;
};
void test_func(struct test *self, uint16_t messageId, unsigned char *buffer, uint32_t bufferSize)
    {
        self->buffer = buffer;
        self->bufferSize = bufferSize;
        self->bufferEnd = 0;

        if (self->bufferSize < MSG_ID_AND_COUNT_SIZE)
            return;

        messageId = htole16(messageId);
        memcpy(self->buffer, &messageId, sizeof(messageId));
        self->bufferEnd += sizeof(messageId);

        uint8_t count = 0;
        memcpy(self->buffer + sizeof(uint16_t), &count, sizeof(count));
        self->bufferEnd += sizeof(count);
    }

Which I want to call in ctypes using Python:

    import ctypes as ct
    class test(ct.Structure):
        _fields_ = [("buffer", ct.c_char_p),
                    ("bufferSize", ct.c_uint32),
                    ("bufferEnd", ct.c_uint32)
    cdll = ct.CDLL("test.so")

    MESSAGE_BUFFER_SIZE = 65535
    message_buffer = ct.create_string_buffer(MESSAGE_BUFFER_SIZE)
    cdll.test_func.argtypes = [ct.POINTER(test), ct.c_uint16, ct.c_char_p, ct.c_uint32]
    cdll.test_func.restype = None

    # calling the function
    test_struc = test()
    cdll.test_func(ct.byref(test_struc), ct.c_uint16(32768),messsage_buffer,ct.c_uint32(MESSAGE_BUFFER_SIZE))

Afterwards, the buffer property of my test_struc is just an empty b'' string. I suppose this is because my created byte array starts with a zero, and the.value attribute of the string_buffer is null terminated. In the.raw attribute, the correct byte string is seen. Is there any way that afterwards the string as seen in the.raw value is copied to my struct? Thx!

Found the solution, apparently c_char_p is not the same as POINTER(c_char). Using the latter the content of the buffer can then be accessed with ct.string_at() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM