Ctypes: How to convert a c_ubyte array to Python bytes?


I’m working with a C function that returns the pointer (c_void_p) to the first byte of a bitmap buffer with known length, and I wish to access the bitmap data as Python bytes.
I figured out that one can acquire an LP_c_ubyte_Array_[N] using

ctypes.cast(buffer_pointer, ctypes.POINTER(ctypes.c_ubyte * N))

but how can I get a Python bytes object from this ctypes array?


You can simply pass it to bytes(), which will make a copy of the contents. The ctypes objects support the C-API buffer protocol, so a lot of functions taking bytes objects also take these.

Oh yes, you’re right, thanks! I found my mistake: I just forgot to use .contents when passing the array to bytes()