Python:我们能将ctypes结构转换为字典吗?
我有一个 ctypes 结构体。
class S1 (ctypes.Structure):
_fields_ = [
('A', ctypes.c_uint16 * 10),
('B', ctypes.c_uint32),
('C', ctypes.c_uint32) ]
如果我有一个对象 X=S1(),我想从这个对象中返回一个字典。例如,如果我做类似这样的操作:Y = X.getdict() 或者 Y = getdict(X),那么 Y 可能看起来像这样:
{ 'A': [1,2,3,4,5,6,7,8,9,0],
'B': 56,
'C': 8986 }
有人能帮忙吗?
3 个回答
2
你觉得这样怎么样:
class S1(ctypes.Structure):
_fields_ = [ ... ]
def getdict(self):
dict((f, getattr(self, f)) for f, _ in self._fields_)
3
这个内容是说,想要有一个更通用的方法来处理双重数组、结构体数组和位域。
def getdict(struct):
result = {}
#print struct
def get_value(value):
if (type(value) not in [int, 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
12
可能像这样:
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}
你可以看到,它对数字有效,但对数组就没那么好用了——你需要自己处理把数组转换成列表的事情。下面是一个更复杂的版本,它会尝试把数组转换过来:
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
如果你有 numpy
并且想处理多维的 C 数组,你应该加上 import numpy as np
,然后把:
value = list(value)
改成:
value = np.ctypeslib.as_array(value).tolist()
这样你就会得到一个嵌套的列表。