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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With