[Pyrex] getting data pointer to numpy object
Brian Blais
bblais at bryant.edu
Wed Mar 29 15:40:45 CEST 2006
Greg Ewing wrote:
> Brian Blais wrote:
>
>> ...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
>> #-------------------------------
>
> You can declare any variable as an ArrayType,
> not just parameters. So
>
> def test2(d):
> cdef ArrayType w
> cdef double *w_p
> w = d['w']
> w_p = <double *>w.data
>
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
--
-----------------
bblais at bryant.edu
http://web.bryant.edu/~bblais
More information about the Pyrex
mailing list