Вопрос

I am using ctypes to interface with a library. There is a method that needs a passed char buffer to be padded on both sides to write network header/footer in, but the pointer has to point past the pre-padding.

So far I've accomplished that by doing the following:

send_buffer = b'\0' * 18 + payload + b'\0' * 4
ptr = ctypes.cast (send_buffer, ctypes.c_void_p)
ptr.value += 18
lws.libwebsocket_write (wsi, ptr, len (payload), 0)

But this feels like a really evil way to do things.

Is this a correct way to do it?

Это было полезно?

Решение

cast is returning the internal pointer of the Python string. Don't pass an immutable Python string to a function that expects a mutable buffer. Use create_string_buffer to create a mutable char array (read section 16.17.1.4. Fundamental data types). For the offset, use byref with the optional offset argument:

send_buf = ctypes.create_string_buffer(b'\0' * 18 + payload + b'\0' * 4)
lws.libwebsocket_write(wsi, ctypes.byref(send_buf, 18), len(payload), 0)

send_buf.value # null terminated
send_buf.raw   # complete array
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top