0

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?

asked Apr 25, 2018 at 15:49

2 Answers 2

1

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.

answered Apr 25, 2018 at 15:56
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your clarification
1

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.

answered Apr 25, 2018 at 15:54

1 Comment

Thank you for spotting the fact that c pointers are 32 or 64 bit.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.