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

发布于 2021-01-29 14:11:12

我正在尝试将用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))

过去,我对所有可能的dtype进行了丑陋的for循环处理,但我相信应该有更好的方法来执行此操作。

关注者
0
被浏览
109
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    是的,您想使用一种融合类型来让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])
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看