如何获取“类型”来自 ctypes 结构或联合字段的字段描述符
我有一个具有不同数据类型字段的结构。我想迭代结构字段,检查数据类型,并为字段设置适当的值。
我可以通过字段的 .size 和 .offset 属性访问字段的大小和偏移量。如何获取字段的“类型”属性?使用 type(value) 不会打印特定字段的 ctypes 数据类型。如果我打印值,那么我确实看到了 ctypes 数据类型,但似乎没有可以直接访问它的属性。
如何直接访问类型字段描述符?
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'>
理想情况下,我希望获得类似于下面的代码片段的字段类型......
>>> A.one.type
c_long
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.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ctypes API 似乎不支持此功能。创建
Field
repr
时,将从嵌入类型中检索名称,如下所示:对于您的字段,成员
self->proto
指向c_long
,但我在 Python 2.7 的cfield.c
您可以在其中检索self 的值->proto
本身。您可能被迫:name
创建您自己的映射 ->类型
。getattr(ctypes, X)
获取类型对象。只是为了跟进选项 (1) 的示例,这里有一个类装饰器,它为您创建类型映射,添加一个
_typeof(cls, fld)
类方法:结果:
This doesn't appear to be supported in the ctypes API. When the
Field
repr<Field type=c_long ..>
is created, the name is retrieved from the embedded type like this:For your field the member
self->proto
points toc_long
, yet I find no place in Python 2.7'scfield.c
where you can retrieve the value ofself->proto
itself. You may be forced either to:name
->type
.<Field type=X
and usegetattr(ctypes, X)
to fetch the type object.Just to follow up with an example of option (1), here's a class decorator which creates the type mapping for you, adding a
_typeof(cls, fld)
class method:Result:
只需使用
_fields_
列表:Just use the
_fields_
list: