Passing and returning numpy arrays to C++ methods via Cython Passing and returning numpy arrays to C++ methods via Cython numpy numpy

Passing and returning numpy arrays to C++ methods via Cython


You've basically got it right. First, hopefully optimization shouldn't be a big deal. Ideally, most of the time is spent inside your C++ kernel, not in the cythnon wrapper code.

There are a few stylistic changes you can make that will simplify your code. (1) Reshaping between 1D and 2D arrays is not necessary. When you know the memory layout of your data (C-order vs. fortran order, striding, etc), you can see the array as just a chunk of memory that you're going to index yourself in C++, so numpy's ndim doesn't matter on the C++ side -- it's just seeing that pointer. (2) Using cython's address-of operator &, you can get the pointer to the start of the array in a little cleaner way -- no explicit cast necessary -- using &X[0,0].

So this is my edited version of your original snippet:

cimport numpy as npimport numpy as npcdef extern from "myclass.h":    cdef cppclass MyClass:        MyClass() except +        void run(double* X, int N, int D, double* Y)def run(np.ndarray[np.double_t, ndim=2] X):    X = np.ascontiguousarray(X)    cdef np.ndarray[np.double_t, ndim=2, mode="c"] Y = np.zeros_like(X)    cdef MyClass myclass    myclass = MyClass()    myclass.run(&X[0,0], X.shape[0], X.shape[1], &Y[0,0])    return Y