Assuming I have a struct defined as such:
cdef extern from "blah.h":
struct my_struct:
int a
int b
我需要能够将一个dict
转换为my_struct
,而不需要假设任何关于my_struct
字段的知识。换句话说,我需要进行以下转换:
def do_something(dict_arg):
cdef my_struct s = dict_arg
do_somthing_with_s(s)
问题在于Cython无法自动完成此操作:http://docs.cython.org/src/userguide/language_basics.html#automatic-type-conversions 当然,如果我知道
my_struct
字段的名称,我就可以这样做:def do_something(dict_arg):
cdef my_struct s = my_struct(a=dict_arg['a'], b=dict_arg['b'])
do_somthing_with_s(s)
这样做会导致Cython编译器崩溃:
def do_something(dict_arg):
cdef my_struct s = my_struct(**dict_arg)
do_somthing_with_s(s)
我不知道字段名称的原因是因为代码是自动生成的,我不想使用丑陋的hack来处理这种情况。
如何用Cython从Python字典初始化结构体?