如何从ctypes结构或联合字段获取“类型”字段描述符 [英] How to get 'type' field descriptor from ctypes Structure or Union field

查看:113
本文介绍了如何从ctypes结构或联合字段获取“类型”字段描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有不同数据类型字段的结构。我想遍历结构字段,检查数据类型,并将字段设置为适当的值。

I have a structure with different datatype fields. I would like to iterate through the structure fields, check the datatype, and set the field with an appropriate value.

我可以通过以下方式访问字段的大小和偏移量字段的.size和.offset属性。如何获得该字段的类型属性?使用 type(value)不会打印特定字段的ctypes数据类型。如果我打印值,那么我确实看到了ctypes数据类型,但是似乎没有直接访问它的属性。

I have access to the size and offset of the field through the .size and .offset attribute of the field. How can I get the 'type' attribute of the field? Using type(value) does not print the ctypes datatype for the particular field. If I print value then I do see the ctypes datatype but there doesn't seem to be an attribute to access this directly.

如何我直接访问类型字段描述符吗?

How can I access the type field descriptor directly?

from ctypes import *

class A(Structure):
    _fields_ = [("one", c_long),
                ("two", c_char),
                ("three", c_byte)]

>>> A.one
<Field type=c_long, ofs=0, size=4>
>>> A.one.offset
0
>>> A.one.size
4
>>> type(A.one)
<class '_ctypes.CField'>

理想情况下,我想获取类似于以下代码段的字段类型...

Ideally I would like to get the field type similar to the snippet below...

>>> A.one.type
c_long


推荐答案

使用 _fields _ 列表:

>>> for f,t in A._fields_:
...  a = getattr(A,f)
...  print a,a.offset,a.size,t
...
<Field type=c_long, ofs=0, size=4> 0 4 <class 'ctypes.c_long'>
<Field type=c_char, ofs=4, size=1> 4 1 <class 'ctypes.c_char'>
<Field type=c_byte, ofs=5, size=1> 5 1 <class 'ctypes.c_byte'>

这篇关于如何从ctypes结构或联合字段获取“类型”字段描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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