如果你真的需要这样做(可能会考虑重构,所以你不需要)-你需要某种
PyObject
存储c函数指针。
这个
PyCapsule
api提供了一种在python空间中传递不透明指针的方法。我可能会做这样的事,我可能漏掉了一些安全检查
%%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)
用法
wrapped_f
# Out[90]: <capsule object "f" at 0x0000000015ACFE70>
py_myfunc(2, wrapped_f)
# Out[91]: 24.0