我有一个包含许多字段的 ctypes 结构,效果非常好,但是当尝试动态读取字段时,我不知道该怎么做。
简化示例:
from ctypes import *
class myStruct(Structure):
_fields_ = [
("a", c_int),
("b", c_int),
("c", c_int),
("d", c_int)
]
myStructInstance = myStruct(10, 20, 30, 40)
field_to_read = input() #user types in "c", so field_to_read is now set to "c"
print(myStructInstance.field_to_read) #ERROR here, since it doesn't pass the value of field_to_read
这给出了一个属性错误“AttributeError: 'myStruct' object has no attribute 'field_to_read'
有没有办法从 ctypes 结构中动态获取字段?
最佳答案
getattr(obj,name)
是查找对象属性的正确函数:
from ctypes import *
class myStruct(Structure):
_fields_ = [
("a", c_int),
("b", c_int),
("c", c_int),
("d", c_int)
]
myStructInstance = myStruct(10, 20, 30, 40)
field_to_read = input() #user types in "c", so field_to_read is now set to "c"
print(getattr(myStructInstance,field_to_read))
关于python - 如何从ctypes结构中动态读取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142319/