Ctypes: Fast Way To Convert A Return Pointer To An Array Or Python List
I am using ctypes to pass an array pointer to a dll and return a pointer to an array of doubles that was created using malloc in the dll. On return to Python, I need a fast way to
Solution 1:
Slicing a ctypes array or pointer will automatically produce a list:
list_of_results = ret_ptr[:320000]
Depending on what you mean by "convert the pointer to an array" and what output types you can work with, you may be able to do better. For example, you can make a NumPy array backed by the buffer directly, with no data copying:
buffer_as_ctypes_array = ctypes.cast(ret_ptr, ctypes.POINTER(ctypes.c_double*320000))[0]
buffer_as_numpy_array = numpy.frombuffer(buffer_as_ctypes_array, numpy.float64)
This will of course break horribly if you deallocate the buffer while something still needs it.
Post a Comment for "Ctypes: Fast Way To Convert A Return Pointer To An Array Or Python List"