我正在编写一个 Python 脚本,该脚本旨在打印结构中的所有值以及值名称。结构中的值都是 ctypes,但我无法打印它们。就目前而言,当我运行以下代码时
import ctypes
class test(ctypes.Structure):
pass
test._fields_ = [
('a', ctypes.c_float),
('b', ctypes.c_float),
('c', ctypes.c_float)]
d = test(1, 2, 3)
for field in d._fields_:
print field[0], field[1].value
我明白了
a <attribute 'value' of '_ctypes._SimpleCData' objects>
b <attribute 'value' of '_ctypes._SimpleCData' objects>
c <attribute 'value' of '_ctypes._SimpleCData' objects>
有什么想法吗?我认为 .value 应该从 ctypes 对象中获取值,但它似乎不想...
谢谢!
最佳答案
_fields_
具有字段名称和数据类型。您需要名称,对于值,请使用内置的 getattr
:
>>> for name, dtype in d._fields_:
... print name, getattr(d, name)
...
a 1.0
b 2.0
c 3.0
关于Python ctypes c_float.value 不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19988196/