Oren
Oren

Reputation: 94

How to dynamically read field from ctypes structure

I have a ctypes structure with many fields which works wonderfully, but when trying to dynamically read a field I can't figure out how to do it.

Simplified example:

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

This gives an attribute error "AttributeError: 'myStruct' object has no attribute 'field_to_read'

is there a way to dynamically get a field from a ctypes structure?

Upvotes: 1

Views: 1424

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177725

getattr(obj,name) is the correct function to look up an attribute on an object:

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))

Upvotes: 2

luthierBG
luthierBG

Reputation: 174

How about dataclass and eval()?

sample

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}"))

Output example

> b
20

Upvotes: -1

Related Questions