[Pyrex] getting data pointer to numpy object

Filip Wasilewski filip at ftv.pl
Wed Mar 29 17:54:24 CEST 2006


Hello Brian,


> I tried this, and got some warnings, and the code didn't work. I get the compile-time
> warning of:

> test3.c:78: warning: use of cast expressions as lvalues is deprecated

> (along with all of the other, normal, Pyrex compile warnings)

> I am including the code here:


> #test3.pyx

> 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 fun1(d):


>      cdef ArrayType W
>      cdef double *w
>      cdef int i,l

>      W=d['w']
>      w=<double *>W.data
>      l=W.dimensions[0]*W.dimensions[1]

>      for i from 0 <= i < l:

>          print "%.4e" % w[i]


> #=================================================

> #run_test3.py
> import numpy
> import test3

> w=numpy.arange(0,2,.5)
> d={"w":w}

> test3.fun1(d)


> #===================================================

> #output from program:
>>>> execfile('run_test3.py')
> 0.0000e+00
> 5.0000e-01
> 1.0000e+00
> 1.5000e+00
> 8.3394e-312
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 1.9354e+01
> 5.3216e-315
> 0.0000e+00
> 2.1127e+01
> 5.3428e-315
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> 0.0000e+00
> -5.1923e+00
> 2.5548e+02

The code works just fine for me. What's more it works even better if a
2D double numpy array is passed to the fun1 function.

#run_test3.py
import numpy
import test3

w=numpy.array([[1.,2.,3.],[4.,5.,6.]])
d={"w":w}

test3.fun1(d)

##
prints:
1.0000e+000
2.0000e+000
3.0000e+000
5.0000e+000
6.0000e+000
7.0000e+000

Just check in the Pyrex code if the passed array has correct attributes
(nd == 2, type is double, array is contiguous).

I am using patched version of Pyrex so I don't get warnings for lvalues.

Some reading:

Here is an example how to handle numpy arrays in Pyrex
http://new.scipy.org/Wiki/Cookbook/Pyrex_and_NumPy.

You may also wish to consider accessing array objects via array
interface
http://numeric.scipy.org/array_interface.html
http://new.scipy.org/Wiki/Cookbook/ArrayStruct_and_Pyrex

Write if you need more resources.

-- 
Best,
Filip Wasilewski




More information about the Pyrex mailing list