0

Let's say I have the code snippet:

ctypedef double (*scalar_func)(double)

cdef double c_func(scalar_func f):
    return f(1.0)


def call_from_py(py_f):
    cdef scalar_func f = py_f
    return c_func(f)

Here, I want to pass the Python function py_f to c_func. However, this yields the error

Error compiling Cython file:
------------------------------------------------------------
...
cdef double c_func(scalar_func f):
    return f(1.0)


def call_from_py(py_f):
    cdef scalar_func f = py_f
                     ^
------------------------------------------------------------

/Users/david/.ipython/cython/_cython_magic_39903ba379ce438d042b67efa2d500fe.pyx:9:22: Cannot convert Python object to 'scalar_func'

How can I pass a Python function to c_func, i.e. how can I convert a Python function to a C function pointer?

user39628
  • 11
  • 3
  • You can't. A Python function has a whole bunch of state that just annot be represented in a C function pointer. – DavidW Aug 12 '21 at 15:29
  • I know the linked question is C++ rather than C. That just excludes the possibility of using std::function but leaves two other options. – DavidW Aug 12 '21 at 15:36

0 Answers0