1

我有一个包含许多字段的 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'对象没有属性'field_to_read'

有没有办法从 ctypes 结构中动态获取字段?

4

2 回答 2

2

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))
于 2019-09-30T00:10:31.040 回答
-1

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

于 2019-09-28T00:07:26.183 回答