how to pass numpy array to Cython function correctly?

前端 未结 1 1481
感动是毒
感动是毒 2020-12-30 05:55

This is described in many places but i simply cannot get it to work. I am calling a C++ function from Cython:

cimport numpy as np
cdef extern from \"test.h\"         


        
相关标签:
1条回答
  • 2020-12-30 06:11

    For 2D arrays, you just need the ndim keyword:

    cdef np.ndarray[double, mode="c", ndim=2]
    

    The result may or may not share memory with the original. If it shares memory with the original, then the array may not be contiguous, or may have an unusual striding configuration. In this case, passing the buffer to C/C++ directly will be disastrous.

    You should always use ascontiguousarray unless your C/C++ code is prepared to deal with non-contiguous data (in which case you will need to pass in all relevant stride data from Cython into the C function). If the input array is already contiguous, no copy will be made. Make sure to pass a compatible dtype to ascontiguousarray so that you don't risk a second copy (e.g. having to convert from a contiguous float array to a contiguous double array).

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