如何从ctypes结构动态读取字段

时间:2019-09-27 23:52:13

标签: python ctypes

我有一个包含许多字段的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结构中动态获取字段?

2 个答案:

答案 0 :(得分:2)

vector<int> a = { 1, 2, 3 }; vector<int> b(std::move(a)); //std::cout << a.back(); <- Invalid call. We don't know whether a is empty. a.clear(); // Ok. clear() doesn't require preconditions. a.push_back(0); //Ok. Now a is { 0 } 是在对象上查找属性的正确函数:

getattr(obj,name)

答案 1 :(得分:1)

dataclasseval()怎么样?

样本

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