2013-01-02 12 views
17

paramが関数であることをCythonコンパイラに伝える方法はありますか?何かのように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 
関連する問題