Python Cython中有函数类型吗?
有没有办法告诉Cython编译器param是函数。差不多Python Cython中有函数类型吗?,python,callback,cython,Python,Callback,Cython,有没有办法告诉Cython编译器param是函数。差不多 cpdef float calc_class_re(list data, func callback) 应该不言自明……?:) 如果所有其他方法都失败了,您可能需要使用Ctypedef。也许有一种更好的纯Cython方法。你是指python函数还是c函数?当函数签名已知时,“delnan”的注释将适用于c。对于cdef或cpdef函数,c样式的functype应该可以工作。比如ctypedef(*my_func_type)(obje
cpdef float calc_class_re(list data, func callback)
应该不言自明……?:)
如果所有其他方法都失败了,您可能需要使用C
typedef
。也许有一种更好的纯Cython方法。你是指python函数还是c函数?当函数签名已知时,“delnan”的注释将适用于c。对于cdef
或cpdef
函数,c样式的functype应该可以工作。比如ctypedef(*my_func_type)(object、int、float、str)
。对于纯python函数,您需要使用对象
类型。“对于cdef或cpdef函数,C风格的functype应该可以工作。”@NiklasR,您能给出详细的示例吗?
# Define a new type for a function-type that accepts an integer and
# a string, returning an integer.
ctypedef int (*f_type)(int, str)
# Extern a function of that type from foo.h
cdef extern from "foo.h":
int do_this(int, str)
# Passing this function will not work.
cpdef int do_that(int a, str b):
return 0
# However, this will work.
cdef int do_stuff(int a, str b):
return 0
# This functio uses a function of that type. Note that it cannot be a
# cpdef function because the function-type is not available from Python.
cdef void foo(f_type f):
print f(0, "bar")
# Works:
foo(do_this) # the externed function
foo(do_stuff) # the cdef function
# Error:
# Cannot assign type 'int (int, str, int __pyx_skip_dispatch)' to 'f_type'
foo(do_that) # the cpdef function