Skip to content


robertwb edited this page · 15 revisions
Clone this wiki locally

Note: a much easier way of going about this is at .

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 *>
    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

use like

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


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).


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

More information

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


and the soon to be deprecated:


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

Something went wrong with that request. Please try again.