开发者

How to initialize a struct from a dict in cython

开发者 https://www.devze.com 2023-02-25 04:49 出处:网络
Assuming I have a struct defined as such: cdef extern from \"blah.h\": struct my_struct: int a int b I need to be able to convert a dict into my_struct, without assuming any knowledge of my_struct\

Assuming I have a struct defined as such:

cdef extern from "blah.h":
    struct my_struct:
        int a
        int b

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)

The problem is that Cython won't do it: http://docs.cython.org/src/userguide/language_basics.html#automatic-type-conversions

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)

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 开发者_如何学Pythonknow the field's name is because the code is autogenerated, and I don't want to make an ugly hack to handle this case.

How to initialize a struct from a Python dict with Cython ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消