繁体   English   中英

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

[英]Using Cython to wrap a c++ template to accept any numpy array

我正在尝试将用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循环处理,但是我相信应该有更好的方法来执行此操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM