Can a cdef
Cython function be passed to another (python def
) cython function from a Python script?
Minimal example:
test_module.pyx
cpdef min_arg(f, int N):
cdef double x = 100000.
cdef int best_i = -1
for i in range(N):
if f(i) < x:
x = f(i)
best_i = i
return best_i
def py_f(x):
return (x-5)**2
cdef public api double cy_f(double x):
return (x-5)**2
test.py
import pyximport; pyximport.install()
import testmodule
testmodule.min_arg(testmodule.py_f, 100)
This works well, but I want to be able to also do
testmodule.min_arg(testmodule.cy_f, 100)
from a test.py, to have cython's speed (no Python overhead for each f(i)
call). But obviously, Python doesn't know about cy_f, because it's not def
or cpdef
declared.
I was hoping something like this existed:
from scipy import LowLevelCallable
cy_f = LowLevelCallable.from_cython(testmodule, 'cy_f')
testmodule.min_arg(cy_f, 100)
But this gives TypeError: 'LowLevelCallable' object is not callable
.
Thank you in advance.