• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助1

问题说明

我有一个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 }

有什么帮助吗?

正确答案

#1

可能是这样的:

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
系列文章
更多 icon
同类精品
更多 icon
继续加载