Using Cython to port a C ++ template to accept any numpy array

I am trying to wrap a parallel view written in C ++ as a template, use it with numpy arrays of any number type. I am trying to use Cython for this.

My problem is that I don’t know how to pass a pointer to numpy array data (of the correct type) to a C ++ template. I believe that fused types should be used for this, but I don’t quite understand how to do this.

Code in .pyx file 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)) 

In the past, I have done similar tasks with ugly for-loops on all possible dtypes types, but I believe that there should be a better way to do this.

+6
source share
1 answer

Yes, you want to use a fused type so that Cython invokes a sorting pattern for the appropriate pattern specialization. Here's a working example for all non-complex data types that do 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]) 
+4
source

Source: https://habr.com/ru/post/982808/


All Articles