# WrappingNumpy

robertwb edited this page · 15 revisions
##### Clone this wiki locally

Note: a much easier way of going about this is at http://wiki.cython.org/tutorials/numpy .

Let's show it on an example, that takes Python numpy array of floats, converts it to C double array, sums the elements and modifies it in place and returns everything back to Python.

Create `matrix.pyx`:

```cdef extern from "numpy/arrayobject.h":
ctypedef int intp
ctypedef extern class numpy.ndarray [object PyArrayObject]:
cdef char *data
cdef int nd
cdef intp *dimensions
cdef intp *strides
cdef int flags
def mysum(ndarray a):
cdef double *p = <double *>a.data
cdef int dim = a.dimensions[0]
cdef double s=0
for i from 0 <= i < dim:
s += p[i]
p[0] = 13.
return s
```

Compile with:

```cython matrix.pyx
gcc -O3 -I/usr/include/python2.4/ -I/usr/lib/python2.4/site-packages/numpy/core/include/numpy/ -c -o matrix.o matrix.c
gcc -shared matrix.o -o matrix.so
```

use like

```\$ cat t.py
from numpy import array
from matrix import mysum
a = array([1., 2., 3., -8])
print a
print mysum(a)
print a
\$ python t.py
[ 1.  2.  3. -8.]
-2.0
[ 13.   2.   3.  -8.]
```

## Alternative

One can also cimport the numpy types from the c_numpy.pxd file (for example in Debian it is located at /usr/share/doc/python-numpy/pyrex/c_numpy.pxd).

## Discussion

This would be very nice to grow up into an example of manipulating an array of extension types.

Other examples are in the numpy upstream tarball in the directory:

```numpy/doc/cython
```

and the soon to be deprecated:

```numpy/doc/pyrex
```

You can also browse the sources of Sage, which is a production usage of Cython.

Something went wrong with that request. Please try again.