Python cast byte array to C void pointer

3 weeks ago 24
ARTICLE AD BOX

In python I can easily cast bytes object to void pointer:

import ctypes; ptr = ctypes.cast(bytes(16), ctypes.c_void_p)

however, bytes are an immutable object.

Surprizingly, bytearray cannot be cast to void pointer, and the followed instruction:

ptr = ctypes.cast(bytearray(16), ctypes.c_void_p)

causes the error:

# TypeError: 'bytearray' object cannot be interpreted as ctypes.c_void_p

I suppose this is because bytearray is a dynamic array and thus can realloc the underlying memory when size changes, so it's technically "unsafe".

Is there a way to "convince" python that it's ok to cast a bytearray to a void pointer?

Read Entire Article