使用Cython包装c ++模板以接受任何numpy数组

Max*_*aev 6 c++ python arrays numpy cython

我正在尝试将用c ++编写的并行排序作为模板包装,以便将它与任何数字类型的numpy数组一起使用.我正在尝试使用Cython来做到这一点.

我的问题是我不知道如何将指向numpy数组(正确类型)的指针传递给c ++模板.我相信我应该使用融合dtypes,但我不太明白.

.pyx文件中的代码如下

# importing c++ template
cdef extern from "test.cpp":
    void inPlaceParallelSort[T](T* arrayPointer,int arrayLength)

def sortNumpyArray(np.ndarray a):
    # This obviously will not work, but I don't know how to make it work. 
    inPlaceParallelSort(a.data, len(a))
Run Code Online (Sandbox Code Playgroud)

在过去,我对所有可能的dtypes进行了类似的丑陋循环,但我相信应该有更好的方法来做到这一点.

Ian*_*anH 5

是的,您想使用融合类型让 Cython 为模板的适当专业化调用排序模板。这是所有非复杂数据类型的工作示例,它使用std::sort.

# cython: wraparound = False
# cython: boundscheck = False

cimport cython

cdef extern from "<algorithm>" namespace "std":
    cdef void sort[T](T first, T last) nogil

ctypedef fused real:
    cython.char
    cython.uchar
    cython.short
    cython.ushort
    cython.int
    cython.uint
    cython.long
    cython.ulong
    cython.longlong
    cython.ulonglong
    cython.float
    cython.double

cpdef void npy_sort(real[:] a) nogil:
    sort(&a[0], &a[a.shape[0]-1])
Run Code Online (Sandbox Code Playgroud)