2013-01-02 81 views
17

有沒有什麼辦法可以告訴Cython編譯器param是函數。像在Cython中是否有任何類型的函數?

cpdef float calc_class_re(list data, func callback) 
+0

如果一切都失敗了,你可以搭載一個C'typedef'。儘管如此,可能會有更好的純Cython方法。 – delnan

+0

你是指python函數還是c函數?當函數簽名已知時,「delnan」的註釋將對c有效。 – shaunc

+0

對於'cdef'或'cpdef'函數,C風格的functype應該可以工作。像'ctypedef(* my_func_type)(object,int,float,str)'。您需要爲純Python函數使用'object'類型。 –

回答

27

應該是不言自明的..? :)

# 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 
相關問題