[Numpy-discussion] Cython: Passing numpy array into C via buffer?

Dag Sverre Seljebotn dagss@student.matnat.uio...
Fri Sep 26 05:57:44 CDT 2008

Richard Shaw wrote:
> Hello,
> Forgive me if this is a stupid question, I've been looking around all 
> the Cython documentation and I can't find out if this is possible.
> What I would like to do is generally is wrap a C function that takes a 
> double array, and be able to pass in a numpy array, I was wondering if 
> it's possible to do this using the buffer interface? I understand I 
> could do it using this method (http://wiki.cython.org/WrappingNumpy), 
> but the buffer interface seems much neater.
> Specifically, I have a C function that I would like to wrap with signature:
> #### cfile.h
> double do_something(double * array, int len);
> I was hoping with the buffer interface, I could do something like this:
> #### pyfile.pyx
> import numpy
> cimport numpy
> cdef extern from "cfile.h"
> 	double do_something(double * array, int len)
> cdef do_something_python(numpy.ndarray[numpy.float64, ndim = 1] numarr):
> 	cdef double x
> 	cdef double * data
> 	cdef int l
> 	data = ... # Not sure what to do here
> 	l = numarr.shape[0]
> 	x = do_something(data, l)

I'm sorry, my previous answer was a really, really bad one. Here's a 
better one:

data = <double*>numarr.data

:-) With the addition of the _t on float64 this should just work.

Please insert an extra check to make sure that your data is contiguous 
though! Otherwise you need to make a copy to pass the data to an 
external lib (one way is by using numpy.array with a contiguouos 
argument to construct a copy, and then copy the data back again afterwards).

Dag Sverre

More information about the Numpy-discussion mailing list