I have an external library that computes the optima, say minima, of a given function. Say its headers give me a function
double[] minimizer(ObjFun f)
where the headers define
typedef double (*ObjFun)(double x[])
I have generated Cython wrappers for this library. I now want to give user parameterized functions to it, specifically, I want to write a function
def getFunction(double q11, double q12, double q22):
cdef f(double x[]):
return x[0]*x[0]*q11 + 2*x[0]*x[1]*q12 + x[1]*x[1]*q22
return f
that the user calls with their parameters (q11, q12, q22) to get a function that can be used as a callback for the C optimization library.
(The example above is contrived and simplified, the whole point of doing this in Cython is that I want nearly-C-efficient callbacks to give to the library.)
There is no way to do this in C, as observed by people in my other question. But in Cython I can compile this:
cdef class Quadratic:
cdef double q11
cdef double q12
cdef double q22
def __cinit__(self, double a, double b, double c):
self.q11 = a
self.q12 = b
self.q22 = c
cdef f(self, double x[]):
return self.q11*x[0]*x[0] + self.q12*x[0]*x[1] + self.q22*x[1]*x[1]
(I have not yet tried using a generated function like this as an input to the library).
My question - is there Python overhead in this evaluation? I would like to have the parameterized function be nearly as efficient as if it were written in C.
If that is possible, how does Cython achieve this?