I'm trying to wrap a parallel sort written in c++ as a template, to use it with numpy arrays of any numeric type. I'm trying to use Cython to do this.
我正在尝试将用c ++编写的并行排序作为模板包装,以便将它与任何数字类型的numpy数组一起使用。我正在尝试使用Cython来做到这一点。
My problem is that I don't know how to pass a pointer to the numpy array data (of a correct type) to a c++ template. I believe I should use fused dtypes for this, but I don't quite understand how.
我的问题是我不知道如何将指向numpy数组(正确类型)的指针传递给c ++模板。我相信我应该使用融合dtypes,但我不太清楚如何。
The code in .pyx file is below
.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))
In the past I did similar tasks with ugly for-loops over all possible dtypes, but I believe there should be a better way to do this.
在过去,我在所有可能的dtypes上做了类似的丑陋for循环任务,但我相信应该有更好的方法来做到这一点。
1 个解决方案
#1
4
Yes, you want to use a fused type to have Cython call the sorting template for the appropriate specialization of the template. Here's a working example for all non-complex data types that does this with std::sort
.
是的,您希望使用融合类型让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])
#1
4
Yes, you want to use a fused type to have Cython call the sorting template for the appropriate specialization of the template. Here's a working example for all non-complex data types that does this with std::sort
.
是的,您希望使用融合类型让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])