Python:我们可以将ctypes结构转换为字典吗? [英] Python: Can we convert a ctypes structure to a dictionary?

查看:276
本文介绍了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.

这篇关于Python:我们可以将ctypes结构转换为字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆