由于历史原因,我保留了我的其他答案-
它表明,不进行jit编译就无法执行您想要的操作,并帮助我了解@DavidW在此答案中)的建议有多么出色。
为了简单起见,我使用功能的签名稍微简单一些,并相信您可以根据需要对其进行更改。
这是关闭的蓝图,它允许
ctypes在后台进行jit编译:
%%cython#needs Cython > 0.28 to run because of verbatim C-pre cdef extern from *: #fill some_t with life """ typedef int (*func_t)(int); static int some_f(func_t fun){ return fun(42); } """ ctypedef int (*func_t)(int) int some_f(func_t myFunc)#works with any recent Cython version:import ctypescdef class Closure: cdef object python_fun cdef object jitted_wrapper def inner_fun(self, int arg): return self.python_fun(arg) def __cinit__(self, python_fun): self.python_fun=python_fun ftype = ctypes.CFUNCTYPE(ctypes.c_int,ctypes.c_int) #define signature self.jitted_wrapper=ftype(self.inner_fun)#jit the wrapper cdef func_t get_fun_ptr(self): return (<func_t *><size_t>ctypes.addressof(self.jitted_wrapper))[0]def use_closure(Closure closure): print(some_f(closure.get_fun_ptr()))现在使用它:
>>> cl1, cl2=Closure(lambda x:2*x), Closure(lambda x:3*x)>>> use_closure(cl1)84>>> use_closure(cl2)126



