Passing Numpy arrays to C code wrapped with Cython Passing Numpy arrays to C code wrapped with Cython arrays arrays

Passing Numpy arrays to C code wrapped with Cython


You probably want Cython's "typed memoryviews" feature, which you can read about in full gory detail here. This is basically the newer, more unified way to work with numpy or other arrays. These can be exposed in Python-land as numpy arrays, or you can export them to Python (for example, here). You have to pay attention to how the striding works and make sure you're consistent about e.g. C-contiguous vs. FORTRAN-like arrays, but the docs are pretty clear on how to do that.

Without knowing a bit more about your function it's hard to be more concrete on exactly the best way to do this - i.e., is the C function read-only for the arrays? (I think yes based on the signature you gave, but am not 100% sure.) If so you don't need to worry about making copies if needed to get C-contiguous states, because the C function doesn't need to talk back to the Python-level numpy array. But typed memoryviews will let you do any of this with a minimum of fuss.


The cython interface code should be created according to the tutorial given here.

To get a C pointer to the data in a numpy array, you should use the ctypes attribute of the numpy array, which is described here.