steve
steve

Reputation: 153

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?

Upvotes: 0

Views: 610

Answers (2)

CristiFati
CristiFati

Reputation: 41116

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.

Upvotes: 1

FHTMitchell
FHTMitchell

Reputation: 12147

lst is now a python bytes object, not a numpy array. Thats what .tobytes() does.

Why not do

lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5))
lst.ctypes.data_as(ctypes.c_void_p)

?

I'm not even sure why you tried to convert to a byte which is 8 bit when c pointers are 32 or 64 bit.

Upvotes: 1

Related Questions