I have a structure (by Mark Tolonen, great thanks to him!). (I've decided to not rewrite it here, to avoid code duplication with that post). The feature of this structure is that structure may include another structures and arrays and even array with structures.
I've tried to create a function, which will convert this structure to python dict. Here is the trying:
def _process_ctypes(self, ctypes_obj):
if isinstance(ctypes_obj, ctypes.Structure):
data_dict = {}
for field_name, field_type in ctypes_obj.get_fields():
field_value = getattr(ctypes_obj, field_name)
if isinstance(field_value, (ctypes.Structure, ctypes.Array)):
data_dict[field_name] = self._process_ctypes(field_value)
else:
data_dict[field_name] = field_value
return data_dict
elif isinstance(ctypes_obj, ctypes.Array):
data_list = []
for element in ctypes_obj:
if isinstance(element, (ctypes.Structure, ctypes.Array)):
data_list.append(self._process_ctypes(element))
else:
data_list.append(element)
return data_list
But, it looks kinda ugly-complicated imho. And it's not possible to add some data to the final output, only outside a function.
Do you have any ideas how to simplify and refactor this function, which will recursively go through the entire C structure and collect a dictionary of all nested structures and arrays of values? Input - always ctypes.Structure, output - always python.dictionary.
In addition, it would be great to convert every array into the dictionary too, just using some specific strings as keys.