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

标签 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' 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/

相关文章:

python - 如何使用 ctypes 从 Python3 访问 C 中的某些常量值

Python ctypes 'c_char_p' 内存泄漏

python - 使用前一个单元格的最接近值填充数据帧的空单元格

python - “iter() returned non-iterator” 用于动态绑定(bind) `next` 方法

python - 如何解析 csv 文件并根据该数据计算统计信息

python - 为什么 refs 在 Python 中每个新对象都会增加 2?

python - 如何调试我使用 ctypes 从 Python 调用的 Visual Studio 中的 DLL?

python - 在 python 程序中通过 ctypes 使用具有线程本地存储的共享库时发生内存泄漏

python - 在 Django 中处理静态文件

python - Eclipse 和 Python 3 : why does printf() from ctypes display in console output after subsequent print() statements