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

从ctypes结构或联合字段获取“类型”字段描述符

用户头像
it1352
帮助1

问题说明

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

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

正确答案

#1

使用 _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'>

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfigjg
系列文章
更多 icon
同类精品
更多 icon
继续加载