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

前端 未结 1 1697
忘掉有多难
忘掉有多难 2021-01-30 09:21

There are lots of questions about using numpy in cython on this site, a particularly useful one being Simple wrapping of C code with cython.

However, the cython/numpy in

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 09:45

    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 np
    import numpy as np
    
    cdef 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
    

    0 讨论(0)
提交回复
热议问题