I am using a Python (via ctypes
) wrapped C library to run a series of computation. At different stages of the running, I want to get data into Python, and specifically numpy
arrays.
The wrapping I am using does two different types of return for array data (which is of particular interest to me):
ctypes
Array: When I dotype(x)
(where x is thectypes
array, I get a<class 'module_name.wrapper_class_name.c_double_Array_12000'>
in return. I know that this data is a copy of the internal data from the documentation and I am able to get it into anumpy
array easily:>>> np.ctypeslib.as_array(x)
This returns a 1D numpy
array of the data.
ctype
pointer to data: In this case from the library's documentation, I understand that I am getting a pointer to the data stored and used directly to the library. Whey I dotype(y)
(where y is the pointer) I get<class 'module_name.wrapper_class_name.LP_c_double'>
. With this case I am still able to index through the data likey[0][2]
, but I was only able to get it into numpy via a super awkward:>>> np.frombuffer(np.core.multiarray.int_asbuffer( ctypes.addressof(y.contents), array_length*np.dtype(float).itemsize))
I found this in an old numpy
mailing list thread from Travis Oliphant, but not in the numpy
documentation. If instead of this approach I try as above I get the following:
>>> np.ctypeslib.as_array(y)
...
... BUNCH OF STACK INFORMATION
...
AttributeError: 'LP_c_double' object has no attribute '__array_interface__'
Is this np.frombuffer
approach the best or only way to do this? I am open to other suggestions but must would still like to use numpy
as I have a lot of other post-processing code that relies on numpy
functionality that I want to use with this data.
ctype
array. Any recommendations? – dtlussier Dec 4 '10 at 20:09numpy.ctypeslib.ndpointer
as argument type to the ctypes wrapper of your function. (If this is not clear, just ask...) – Sven Marnach Dec 4 '10 at 20:46