How Do I Convert A Pointer Returned By A C Function Invoked Using Ctypes Into A Numpy Array?
I have a function in C which returns an array of data and its length. Everything compiles and works fine and I can invoke the function. >>> from ctypes import * >>&g
Solution 1:
I finally found the way:
# CALLING C FUNCTION, RETURNS unsignedint *c_data AND int c_length
c_length = c_int()
c_data = c_void_p()
test.get_uint_array(byref(c_data), byref(c_length));
# CONVERT TO NUMPY
data = np.ctypeslib.as_array(cast(c_data, POINTER(c_uint)), shape=(c_length.value,))
Notes:
- Data (
c_data
) must be released later in C usingfree
and thec_data
pointer. - Note how the function returns
unsigned int *
and we handle avoid *
and later cast into a pointer. Not sure if there is a way to directly receive anunsigned int *
pointer and avoid the cast. - adding
.copy()
to the end of the.as_array
method copies the array to the numpy object and data memory allocated by C can be immediately released (so now the memory is handled by Python). This might be useful in certain scenarios but duplicates the memory and there is the overhead of copying data into the new array.
I am still wondering if this is the optimal way of achieving this data conversion. If anyone knows another way to make this more efficient feel free to add comments or post another answer.
Post a Comment for "How Do I Convert A Pointer Returned By A C Function Invoked Using Ctypes Into A Numpy Array?"