在Cython中按名称调用cdef函数 [英] Call cdef function by name in Cython

查看:58
本文介绍了在Cython中按名称调用cdef函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Cython中有一堆 cdef 函数,这些函数由 pyx 文件中的 def 函数调用,例如:

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

这很好.但是为了简化而不必为每个 cdef 函数使用python包装器,我试图通过将名称分配给 cdef 函数进行索引,方法是将它们分配给字典或类似的东西:

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

但这不起作用.Cython抱怨说它不知道 myfunc_c 的类型.

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

是否可以通过名称来索引或调用 cpdef 函数(例如,使用字符串)?我还尝试了 locals()['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.

推荐答案

对于 cdef 函数,这绝对是不可能的-它们仅定义C接口而不是Python接口,因此没有自省功能.

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 函数定义了Python和C接口.在函数内,它们将在 globals()中可用,而不是在 locals()中使用(因为 locals()仅给出该函数中定义的变量)

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.)

我实际上并不认为您想要这样做.我认为您只想使用 cpdef 而不是 cdef ,因为这会自动为该函数生成Python包装器.

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.

这篇关于在Cython中按名称调用cdef函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆