[Numpy-discussion] Getting a numpy array from a ctype pointer
Travis E. Oliphant
oliphant@enthought....
Thu Sep 4 18:21:47 CDT 2008
Paulo J. S. Silva wrote:
> After some trial and erros, I found a solution, described below. Is this
> the best one? Looks a little convoluted to me (C represents ctypes
> module and np numpy):
>
> Array = n*C.c_double
> x = Array.from_address(C.addressof(x.contents))
> x = np.ctypeslib.as_array(x)
>
That's a pretty simple approach. There is a faster approach which uses
the undocumented function int_asbuffer function from numpy.core.multiarray
(i.e. from numpy.core.multiarray import int_asbuffer)
Then:
x = np.frombuffer(int_asbuffer(C.addressof(x.contents), n*8))
If you don't like the hard-coded '8', then you can get that number from
np.dtype(float).itemsize
There may also be a way to get it from ctypes.
-Travis
More information about the Numpy-discussion
mailing list