Search code examples
pythonpython-3.xctypes

Pass byte numpy array to C function using ctypes


I want to pass byte numpy array to a C function using ctypes. The C function takes void *mem_address so I thought to pass it as the following:

lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5))
lst = np.asarray(lst).tobytes()

# Pass
lst.ctypes.data_as(ctypes.c_void_p)

This gives the error AttributeError: 'bytes' object has no attribute 'ctypes' which means ctypes does not handle numpy. Is there a workaround?


Solution

  • lst = np.asarray(lst).tobytes() generates a plain Bytes object ([Python.Docs]: class bytes([source[, encoding[, errors]]]) which is not handled by CTypes.

    The original object (lst) on the other hand ([NumPy]: numpy.ndarray), is.
    So, removing the above line of code, would fix the error.