[Numpy-discussion] Getting a numpy array from a ctype pointer
Paulo J. S. Silva
Thu Sep 4 17:56:17 CDT 2008
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)
Em Qui, 2008-09-04 às 17:31 -0400, Paulo J. S. Silva escreveu:
> Em Qui, 2008-09-04 às 15:01 -0500, Travis E. Oliphant escreveu:
> > Paulo J. S. Silva wrote:
> > >
> > Something like this may work:
> > from numpy import ctypeslib
> > r = ctypeslib.as_array(x._type_ * n)
> Unfortunately, it didn't work.
> > If that doesn't work, then you can create an array from an arbitrary
> > buffer or any object that exposes the __array_interface__ attribute.
> > So, if you can get the address of c_double then you can use it as the
> > data for the ndarray.
> > Ask if you need more help.
> I think I need help. I discovered how to create a Python string from the
> pointer using ctypes' string_at function:
> r = C.string_at(x, n*C.sizeof(x._type_))
> Now I can use numpy fromstring to get a array version of it. However
> this is not enough for my application as fromstring actually copies the
> data, hence change to the array are not reflected in the original array
> that goes back to the Fortran code.
> Any hints?
> Numpy-discussion mailing list
More information about the Numpy-discussion