如何从ctypes结构中动态读取字段
How to dynamically read field from ctypes structure
我有一个包含许多字段的 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 结构中动态获取字段?
dataclass
和 eval()
怎么样?
样本
from dataclasses import dataclass
from ctypes import *
@dataclass
class MyStruct:
a: c_int
b: c_int
c: c_int
d: c_int
my_struct_instance = MyStruct(10, 20, 30, 40)
field_to_read = input()
print(eval(f"my_struct_instance.{field_to_read}"))
输出示例
> b
20
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))
我有一个包含许多字段的 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 结构中动态获取字段?
dataclass
和 eval()
怎么样?
样本
from dataclasses import dataclass
from ctypes import *
@dataclass
class MyStruct:
a: c_int
b: c_int
c: c_int
d: c_int
my_struct_instance = MyStruct(10, 20, 30, 40)
field_to_read = input()
print(eval(f"my_struct_instance.{field_to_read}"))
输出示例
> b
20
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))