## page was renamed from Cookbook/Pyrex And NumPy
Please note that the code described here is slightly out of date, since today [http://cython.org cython] is the actively maintained version of Pyrex, and numpy now ships with Cython examples.
Rather than maintaining both the wiki and the source dir, we'll continue to update the sources, kept [http://projects.scipy.org/scipy/numpy/browser/trunk/numpy/doc/cython here].
== Old Pyrex page ==
[http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Pyrex] is a language for writing C extensions to Python. Its syntax is very similar to writing Python. A {{{.pyx}}} file is compiled to a {{{.c}}} file, which is then compiled like a standard C extension module for Python. Many people find writing extension modules with Pyrex preferable to writing them in C or using other tools, such as SWIG.
This page is a starting point for accessing numpy arrays natively with Pyrex. Please note that with current versions of NumPy (SVN), the directory {{{numpy/doc/pyrex}}} contains a complete working example with the code in this page, including also a proper {{{setup.py}}} file so you can install it with the standard Python mechanisms. This should help you get up and running quickly.
Here's a file I call "c_python.pxd":
{{{#!python numbers=disable
cdef extern from "Python.h":
ctypedef int Py_intptr_t
}}}
and here's "c_numpy.pxd":
{{{#!python numbers=disable
cimport c_python
cdef extern from "numpy/arrayobject.h":
ctypedef class numpy.ndarray [object PyArrayObject]:
cdef char *data
cdef int nd
cdef c_python.Py_intptr_t *dimensions
cdef c_python.Py_intptr_t *strides
cdef object base
# descr not implemented yet here...
cdef int flags
cdef int itemsize
cdef object weakreflist
cdef void import_array()
}}}
Here's an example program, name this something like "test.pyx" suffix.
{{{#!python numbers=disable
cimport c_numpy
cimport c_python
import numpy
c_numpy.import_array()
def print_array_info(c_numpy.ndarray arr):
cdef int i
print '-='*10
print 'printing array info for ndarray at 0x%0lx'%(arr,)
print 'print number of dimensions:',arr.nd
print 'address of strides: 0x%0lx'%(arr.strides,)
print 'strides:'
for i from 0<=iarr.strides[i]
print 'memory dump:'
print_elements( arr.data, arr.strides, arr.dimensions, arr.nd, sizeof(double), arr.dtype )
print '-='*10
print
cdef print_elements(char *data,
c_python.Py_intptr_t* strides,
c_python.Py_intptr_t* dimensions,
int nd,
int elsize,
object dtype):
cdef c_python.Py_intptr_t i,j
cdef void* elptr
if dtype not in [numpy.dtype(numpy.object_),
numpy.dtype(numpy.float64)]:
print ' print_elements() not (yet) implemented for dtype %s'%dtype.name
return
if nd ==0:
if dtype==numpy.dtype(numpy.object_):
elptr = (data)[0] #[0] dereferences pointer in Pyrex
print ' ',