简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM