[Numpy-discussion] Re: getting data pointer to numpy object in Pyrex
Robert Kern
robert.kern at gmail.com
Tue Mar 28 15:06:02 EST 2006
Brian Blais wrote:
> Hello,
>
> I posted this on the Pyrex list, but I figured someone here may be able
> to answer it too.
>
> Is here an easy way, in Pyrex, to get the data pointer to a numpy object
> which is *not* passed as a parameter? For example, I know I can do:
>
> #---------------
> cdef extern from "numpy/arrayobject.h":
>
> struct PyArray_Descr:
> int type_num, elsize
> char type
>
> ctypedef class numpy.ArrayType [object PyArrayObject]:
> cdef char *data
> cdef int nd
> cdef int *dimensions, *strides
> cdef object base
> cdef PyArray_Descr *descr
> cdef int flags
>
> def test1(ArrayType w): # pass a numpy object
>
> cdef double *w_p
>
> # get the pointers
> w_p=<double *>w.data
> #---------------
>
> ...but I would like to do something like...
>
> #-------------------------------
> def test2(d): # pass a python dict
>
> w=d['w'] # get the numpy object
>
> cdef double *w_p
>
> # get the pointers
> w_p=<double *>w.data
> #-------------------------------
>
>
> Is there a way to do this?
You will probably want to use the c_numpy.pxd file in numpy/doc/pyrex/. It has
exposed a bit more of the API than you have. If you have any contributions, we
would like to fold them in.
In general, you would just make a cast like you would for any other C type.
However, you must be sure that the object actually is an array. I think the
following code would work as expected, including the case where d['w'] can't be
turned into an array, but I have not tested it.
cimport c_numpy
import numpy
c_numpy.import_array()
def test2(d):
cdef c_numpy.ndarray w
w = <c_numpy.ndarray>numpy.asarray(d['w'])
# ...
--
Robert Kern
robert.kern at gmail.com
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion
mailing list