1

Currently, I am learning how to call c++ template function from Cython. I have a .h file named 'cos_doubles.h' The file is as follows:

#ifndef _COS_DOUBLES_H
#define _COS_DOUBLES_H
#include <math.h>

template <typename T, int ACCURACY>
void cos_doubles(T * in_array, T * out_array, int size)
{
    int i;
    for(i=0;i<size;i++){
        out_array[i] = in_array[i] * 2;
    }
}

#endif

Indeed the variable ACCURACY does nothing. Now, I want to define a template function in cython that use this cos_doubles function, but only has the typename T as a template. In other words, I want to give the variable ACCURACY a value in my cython code. My .pyx code is some thing like the following

# import both numpy and the Cython declarations for numpy
import numpy as np
cimport numpy as np
cimport cython

# if you want to use the Numpy-C-API from Cython
# (not strictly necessary for this example)
np.import_array()

# cdefine the signature of our c function
cdef extern from "cos_doubles.h":
     void cos_doubles[T](T* in_array, T* out_array, int size)

I know this code has errors, because I did not define the variable of ACCURACY in void cos_doubles[T](T* in_array, T* out_array, int size). But I do not know the gramma how to set it. For example, I want to let ACCURACY = 4. Can anyone tell me how to do this ?

One solution I already have is

cdef void cos_doubles1 "cos_doubles<double, 4>"(double * in_array, double * out_array, int size)
cdef void cos_doubles2 "cos_doubles<int, 4>"(int * in_array, int * out_array, int size)

but I do not define two different functions. Is there any better solution?

  • 1
    Is [this answer](https://stackoverflow.com/questions/41190519/interfacing-c11-array-with-cython/41200186#41200186) any help? Cython doesn't really support integer template parameters. There's a few ways of working round it but none are great – DavidW Aug 11 '18 at 07:16

0 Answers0