使用用Cython包装一个C ++模板接受任何numpy的数组 [英] Using Cython to wrap a c++ template to accept any numpy array

查看:1228
本文介绍了使用用Cython包装一个C ++模板接受任何numpy的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想换用C ++编写为模板并行排序,与任何数值类型的数组numpy的使用它。我试图用用Cython做到这一点。

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.

我的问题是,我不知道如何将指针传递给numpy的阵列数据(正确类型)到C ++模板。我相信我应该用熔融dtypes这一点,但我不太了解。

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.

在.pyx文件中的code低于

The code in .pyx file is below

# 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))

在过去的我做了丑陋的for循环通过所有可能的dtypes相似的任务,但是我相信应该有更好的方式来做到这一点。

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.

推荐答案

是的,你想用一个融合型具有用Cython调用模板分类为模板的相应的专业化。
下面是与这是否所有非复杂数据类型的工作示例的std ::排序

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: 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])

这篇关于使用用Cython包装一个C ++模板接受任何numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆