Call cdef function by name in Cython

梦想的初衷 提交于 2021-01-27 12:42:28

问题


I have a bunch of cdef functions in Cython, that are called by a def function in a pyx file, e.g.:

cdef inline void myfunc_c(...):
    (...)
    return

def wrapper(...):
    myfunc_c(...)
    return

This works well. But to simplify not having to have a python wrapper for each cdef function, I was trying to index the cdef functions by name, either by assigning them to a dictionary or something like:

def wrapper(operation):
    if operation == 'my_func':
        func = myfunc_c
    func(...)
    return

But this doesn't work. Cython complains that it doesn't know the type of myfunc_c.

Is there any way to index or call the cpdef functions by name (e.g. use a string)? I also tried things like locals()['myfunc_c'], but that doesn't work either.


回答1:


For cdef functions this is definitely impossible - they only define a C interface but not a Python interface so there's no introspection available.

cpdef functions define both a Python and a C interface. Within a function they will be available in globals() rather than locals() (since locals() only gives the variables defined in that function.)


I don't actually think you want to do this though. I think you just want to use cpdef instead of cdef since this automatically generates a Python wrapper for the function.



来源:https://stackoverflow.com/questions/46378704/call-cdef-function-by-name-in-cython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!