Python我们可以ctypes结构转换为字典吗
问题说明
我有一个ctypes结构。
I have a ctypes structure.
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可能类似于:
if I have X=S1(), I would like to return a dictionary out of this object: Example, if I do something like: Y = X.getdict() or Y = getdict(X), then Y might look like:
{ 'A': [1,2,3,4,5,6,7,8,9,0],
'B': 56,
'C': 8986 }
有什么帮助吗?
正确答案
可能是这样的:
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}
如您所见,它可以与数字一起使用,但不适用于数组-您将不得不自己将数组转换为列表。尝试转换数组的更复杂的版本如下:
As you can see, it works with numbers but it doesn't work as nicely with arrays -- you will have to take care of converting arrays to lists yourself. A more sophisticated version that tries to convert arrays is as follows:
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作为np
并更改:
If you have numpy
and want to be able to handle multidimensional C arrays, you should add import numpy as np
and change:
value = list(value)
至:
value = np.ctypeslib.as_array(value).tolist()
这将为您提供嵌套列表。
This will give you a nested list.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfjhab
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20