How can I convert a BitString to a ctypes byte array?

I just started with BitString and ctypes, and I have part of the binary file stored in startdata, BitArrayclass.

> print(startdata)
0x0000000109f0000000010605ffff

Now I have to pass this data as-is to the C function, which takes an argument unsigned char *, so I first try to do something like this:

buf = (c_ubyte * len(startdata))()

to do this:

buf_ptr = cast(pointer(buf), POINTER(c_ubyte))

This works, but how to assign byte data from startdatafor this array / buffer that I just created?

This does not work:

> buf = (c_ubyte * len(startdata))(*startdata.bytes)
TypeError: an integer is required
+4
source share
1 answer

A solution is possible here (note that I'm using python 3):

import ctypes

def bitarray_to_ctypes_byte_buffer(data):
    """Convert a BitArray instance to a ctypes array instance"""
    ba = bytearray(data.bytes)
    ba_len = len(ba)
    buffer = (ctypes.c_uint8 * ba_len).from_buffer(ba)
    return buffer

(: bytes ctypes, .bytes data.bytes).

C byref:

byref(buffer)
+3

All Articles