Python:我们可以将ctypes结构转换为字典吗?

G.A*_*.A. 10 python ctypes

我有一个ctypes结构.

class S1 (ctypes.Structure):
    _fields_ = [
    ('A',     ctypes.c_uint16 * 10),
    ('B',     ctypes.c_uint32),
    ('C',     ctypes.c_uint32) ]
Run Code Online (Sandbox Code Playgroud)

如果我有X = S1(),我想从这个对象中返回一个字典:例如,如果我做了类似的事情:Y = X.getdict()或Y = getdict(X),那么Y可能看起来像:

{ 'A': [1,2,3,4,5,6,7,8,9,0], 
  'B': 56,
  'C': 8986 }
Run Code Online (Sandbox Code Playgroud)

有帮助吗?

Tam*_*más 11

可能是这样的:

def getdict(struct):
    return dict((field, getattr(struct, field)) for field, _ in struct._fields_)

>>> x = S1()
>>> getdict(x)
{'A': <__main__.c_ushort_Array_10 object at 0x100490680>, 'C': 0L, 'B': 0L}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它适用于数字,但它不能很好地与数组一起使用 - 您必须自己负责将数组转换为列表.尝试转换数组的更复杂版本如下:

def getdict(struct):
    result = {}
    for field, _ in struct._fields_:
         value = getattr(struct, field)
         # if the type is not a primitive and it evaluates to False ...
         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
             value = list(value)
         elif hasattr(value, "_fields_"):
             # Probably another struct
             value = getdict(value)
         result[field] = value
    return result
Run Code Online (Sandbox Code Playgroud)

如果您有numpy并且希望能够处理多维C数组,则应添加import numpy as np和更改:

 value = list(value)
Run Code Online (Sandbox Code Playgroud)

至:

 value = np.ctypeslib.as_array(value).tolist()
Run Code Online (Sandbox Code Playgroud)

这将为您提供嵌套列表.