Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a struct from a dict in cython

Tags:

struct

cython

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 ?

like image 764
Nicolas Viennot Avatar asked Apr 15 '11 06:04

Nicolas Viennot


1 Answers

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.

like image 127
fabrizioM Avatar answered Oct 16 '22 04:10

fabrizioM