Micropython dictionary to C struct

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
curiouswombat
Posts: 1
Joined: Thu Apr 09, 2020 7:52 pm

Micropython dictionary to C struct

Post by curiouswombat » Thu Apr 09, 2020 7:59 pm

I'm working on a project that requires developing rudimentary Protobuf support for Micropython. I've made an extmod module with a function that accepts a dictionary containing Protobuf message data. Since I'm using an embedded C Protobuf library (nanopb for anyone interested) to bring pb support to Micropython, I need to read the data from the dictionary into struct fields of the message. How can I go about this?

I suspect the answer lies in using the functions from objdict.c, but beyond that I have no idea. Thanks

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Micropython dictionary to C struct

Post by jimmo » Tue Apr 14, 2020 4:30 am

hi,

Yes, exactly what you said about objdict.

Conceptually, the underlying structure is a "map", and "dict" is the Python-level API around it.

So you can either use the dict methods (see py/obj.h)

Code: Select all

size_t mp_obj_dict_len(mp_obj_t self_in);
mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index);
mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value);
mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key);
It would also be worth looking at the implementation of modujson's dump method, which ultimately ends up calling dict_print (in objdict.c), which shows how to use dict_iter_next to iterate the items in the dictionary.

...or you can get the map directly (using mp_obj_dict_get_map) and then use the low-level map function (also in obj.h)

Code: Select all

mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind);

User avatar
RWLTOK
Posts: 53
Joined: Thu Dec 14, 2017 7:24 pm

Re: Micropython dictionary to C struct

Post by RWLTOK » Mon Feb 08, 2021 10:27 pm

Any progress on this curiouswombat?

Post Reply