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

Dag Sverre Seljebotn dagss@student.matnat.uio...
Fri Sep 26 05:51:43 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.

Questions like this should be posted to the Cython list (otherwise us 
Cython developers might easily ignore it, we do not follow everything 
that goes on in numpy-discussion).

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

numpy.float64_t, currently at least.

> 	cdef double x
> 	cdef double * data
> 	cdef int l
> 	data = ... # Not sure what to do here
> 	l = numarr.shape[0]

Yes, I understand this. I definitely plan to make this easier in a 
coming Cython release, i.e. something like

cimport cython
data = cython.buffer.bufptr(array)

I just haven't got there yet.

For now, there's an ugly hack you can do (untested though):


#define GET_BUFPTR_HACK(x) __pyx_bstruct_#x.buf


cdef extern from "your_header.h":
     void* GET_BUFPTR_HACK(x)

data = GET_BUFPTR_HACK(buf)

(The reason this is so horribly ugly is the "#x" in the macro, meaning 
this depends very much of the particular mangling scheme used. This will 
likely break in a future version of Cython, but then 
cython.buffer.butptr should be available.)

Dag Sverre

More information about the Numpy-discussion mailing list