Search code examples
c++templatescython

wrapping c++ function template with Cython


I have a c++ template in .cpp file defined as

template void rank_filter(T* in, T* out, int arr_len, int win_len, int order, Mode mode, T cval, int origin) where Mode is enum.

Following this answer, I am trying to wrap it up by Cython, by a .pyx file:

cimport cython
cimport numpy as np

ctypedef fused numeric_t:
    np.float32_t
    np.float64_t
    np.int32_t
    np.int64_t

@cython.boundscheck(False)  # Deactivate bounds checking
@cython.wraparound(False)  # Deactivate negative indexing.
cdef extern from "_rank_filter_1d.cpp" nogil:
    void rank_filter[T](T* in, T* out, int arr_len, int win_len, int order, Mode mode, T cval, int origin)

def rank_filter_1d(numeric_t[:] in_arr, numeric_t[:] out_arr, int win_len, int order, int mode, numeric_t cval, int origin):
    rank_filter(&in_arr[0], &out_arr[0], in_arr.shape[0], win_len, order, mode, cval, origin)
    return out_arr

unfortunately, running python setup.py build_ext --inplace in the terminal results in an error:

cdef extern from "_rank_filter_1d.cpp" nogil:
    void rank_filter[T](T* in, T* out, int arr_len, int win_len, int order, Mode mode, T cval, int origin)
                           ^
------------------------------------------------------------

rank_filter_1d_cython.pyx:13:27: Expected ')', found 'in'

I tried to add cdef before the void, which did not work well. Any other ideas?


Solution

  • in is a Python keyword so it can't be used as a variable name in Cython.

    There's no real reasons why the argument names you tell Cython about have to match the real C argument names - they're just for documentation.

    Convention would probably be just to change in to in_ to keep the intent obvious.