0
votes

I want to generate a ctypes.Structure from a dict, and the only way I see how to do that is to assign the values 1 element at a time.

import ctypes


class MyStructure(ctypes.Structure):
    _fields_ = [('a', ctypes.c_uint16),
                ('b', ctypes.c_double)]


def generate_structure_from_dict(my_dict):
    my_structure = MyStructure()
    my_structure.a = my_dict['a']
    my_structure.b = my_dict['b']
    return my_structure

However, not only does this produce ugly code when MyStructure has 20+ fields, it also means that every time I change my structure, I have to remember to change my generate_structure_from_dict function.

Is there any way to populate a ctypes.Structure through a loop? Ideally a loop that was able to specify the correct key in the dictionary.