Python: Can we convert a ctypes structure to a dictionary?

后端 未结 3 1350
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 08:02

I have a ctypes structure.

class S1 (ctypes.Structure):
    _fields_ = [
    (\'A\',     ctypes.c_uint16 * 10),
    (\'B\',     ctypes.c_uint32),
    (\'C\',            


        
3条回答
  •  鱼传尺愫
    2021-02-20 08:44

    A little bit more general purpose to handle double arrays, and arrays of structures, and bitfields.

    def getdict(struct):
        result = {}
        #print struct
        def get_value(value):
             if (type(value) not in [int, long, float, bool]) and not bool(value):
                 # it's a null pointer
                 value = None
             elif hasattr(value, "_length_") and hasattr(value, "_type_"):
                 # Probably an array
                 #print value
                 value = get_array(value)
             elif hasattr(value, "_fields_"):
                 # Probably another struct
                 value = getdict(value)
             return value
        def get_array(array):
            ar = []
            for value in array:
                value = get_value(value)
                ar.append(value)
            return ar
        for f  in struct._fields_:
             field = f[0]
             value = getattr(struct, field)
             # if the type is not a primitive and it evaluates to False ...
             value = get_value(value)
             result[field] = value
        return result
    

提交回复
热议问题