如何从cython中的字典初始化结构 [英] How to initialize a struct from a dict in cython
问题描述
假设我有一个这样定义的结构:
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的字段有任何了解。换句话说,我需要进行以下转换:
I need to be able to convert a dict
into my_struct
, without assuming any knowledge of my_struct's fields. In other words, I need the following conversion to happen:
def do_something(dict_arg):
cdef my_struct s = dict_arg
do_somthing_with_s(s)
问题是Cython不会这样做:< a href = http://docs.cython.org/src/userguide/language_basics.html#automatic-type-conversions rel = nofollow noreferrer> http://docs.cython.org/src/userguide/language_basics .html#automatic-type-conversions
The problem is that Cython won't do it: http://docs.cython.org/src/userguide/language_basics.html#automatic-type-conversions
当然,如果我对 my_struct
有所了解字段的名称,我可以这样做:
Of course, If I had knowledge on the my_struct
field's name, I could do this:
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编译器崩溃:
Doing this crashes the cython compiler:
def do_something(dict_arg):
cdef my_struct s = my_struct(**dict_arg)
do_somthing_with_s(s)
我不这样做的原因知道该字段的名称是因为代码是自动生成的,因此我不想进行丑陋的处理以解决这种情况。
The reason why I don't know the field's name is because the code is autogenerated, and I don't want to make an ugly hack to handle this case.
如何初始化结构从使用cython的Python字典中获取?
推荐答案
您必须手动设置结构的每个元素。没有捷径。
如果您的代码是自动生成的,则还应该易于自动生成一个内联函数,即
进行从PyDict到每个结构的转换。
You have to set each element of the structure manually. There are no shortcuts. If your code is auto generated then should be easy to autogenerate also an inline function that does the conversion from PyDict to each of your structs.
这篇关于如何从cython中的字典初始化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!