How to initialize a structure from a dict in cython

Assuming I have a structure defined as such:

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

I need to convert a dict to my_struct without allowing any knowledge of the my_struct fields. In other words, I need the following conversion:

 def do_something(dict_arg): cdef my_struct s = dict_arg do_somthing_with_s(s) 

The problem is that Cython will not do this: http://docs.cython.org/src/userguide/language_basics.html#automatic-type-conversions

Of course, if I knew about the value of the my_struct field, 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) 

Executing this cython compiler failure:

 def do_something(dict_arg): cdef my_struct s = my_struct(**dict_arg) do_somthing_with_s(s) 

The reason I don't know the name of the field is because the code is auto-generated, and I don't want to do an ugly hack to handle this case.

How to initialize a structure from a Python dict using Cython?

+4
source share
1 answer

You must set each element of the structure manually. No shortcuts. If your code is auto-generated, then it should be easy to auto-generate also a built-in function that does the conversion from PyDict to each of your structures.

+6
source

All Articles