Skip to content Skip to sidebar Skip to footer

Cython Memoryviews: Wrapping C Function With Array Parameter To Pass Numpy Array

I am trying to use Cython to wrap c function with an array parameter (quick_sort()), so I can pass a numpy array to it. I've searched the documentation, SO and web for a working, m

Solution 1:

The problem is mainly in "quicksort.pxd" - the definition needs to match that in quicksort.h:

cdef externfrom"quicksort.h":
    voidquick_sort (int* a, int n)

([:] defines it as a memoryview instead, which is a Cythony invention and can't be cast directly to a pointer, as your error says).

You then need to get a pointer from the memoryview in "cy_quicksort.pyx"

defquicksort_c(int[::1] a):
    quicksort.quick_sort(&a[0], a.size) # get address of first element

I've changed the input parameter to [::1] to specify that the elements must be continuous in memory, which I think is what quicksort expects.

(Note - untested, but reasonably simple so should work!)

Post a Comment for "Cython Memoryviews: Wrapping C Function With Array Parameter To Pass Numpy Array"