0

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.

Mika
  • 51
  • 4
  • _"it would be great to convert every array into the dictionary too, just using some specific strings as keys"_ ...how would this part work? what is the content of the arrays, are they a fixed size or something, so you could associate specific position in the array with predefined keys? – Anentropic Jul 21 '23 at 13:41
  • https://github.com/CristiFati/cfpyutils/blob/master/ctypes.py#L41 – CristiFati Jul 21 '23 at 13:48
  • Sorry, i didn't talk about it, but, array's always are 6 items length (but this is not important. i'm trying to create a universal algorithm) About content - it can be either another array, or another structure or just a simple types. The example of this structure can be seen in the link at the beginning of the post – Mika Jul 21 '23 at 13:52
  • @CristiFati Thank you a lot. This is a really good realisation of the console output algorithm. But, to be honest, it represents too beautiful output for my task :) I just need to put the data to the pandas csv. As long it works well with python dict, i want to convert C structure to dict. – Mika Jul 21 '23 at 14:54

0 Answers0