【问题标题】:Using Cython to wrap a c++ template to accept any numpy array使用 Cython 包装 c++ 模板以接受任何 numpy 数组
【发布时间】:2015-04-22 16:04:47
【问题描述】:

我正在尝试将用 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 循环完成了类似的任务,但我相信应该有更好的方法来做到这一点。

【问题讨论】:

    标签: python c++ arrays numpy cython


    【解决方案1】:

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

    【讨论】:

    • 这没有按原样编译,编译器抱怨了很多关于 nogil 的问题。我不得不杀死它,但没有它并行化也能工作。
    • @MaximImakaev 是的,只有当你想在并行循环中调用 Cython 函数时,才真正需要 nogil。没有它,排序函数内部的并行化应该没问题。奇怪的是它不会在那里编译。 Cython 版本可能存在一些差异。我有一个最近的开发版本(非常类似于 0.22),它对我来说很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多