How To Call A Cython Cdef() Function That Contains As A Parameter A Function In Python?
I have a cdef function that has amongst its parameters a function. I am trying to generate a python 'wrapper' function that will call it. I know that defining a function as cpdef()
Solution 1:
If you actually need to this (might think about refactoring so you don't) - you need some kind of PyObject
to store the c function pointer.
The PyCapsule
api provides a way of passing opaque pointers around in python space. Could do something like this, I'm probably missing some safety checks
%%cython
from cpython.pycapsule cimport PyCapsule_New, PyCapsule_GetPointer
ctypedef double (*ftype) (double)
# c function you want to wrapper
cdef double f(double a):
return a + 22.0# wrapper capsule
wrapped_f = PyCapsule_New(<void*>f, 'f', NULL)
cdef cy_myfunc(double x, ftype f):
cdef double result = f(x)
return result
def py_myfunc(double x, object f_capsule):
cdef ftype f = <ftype> PyCapsule_GetPointer(f_capsule, 'f')
return cy_myfunc(x, f)
Usage
wrapped_f
# Out[90]: <capsule object "f" at 0x0000000015ACFE70>
py_myfunc(2, wrapped_f)
# Out[91]: 24.0
Post a Comment for "How To Call A Cython Cdef() Function That Contains As A Parameter A Function In Python?"