I have a C struct in cfile.c as a global variable, and i want to be able to access and change it from a python file.
The c struct in the .h file:
typedef struct _attribute((packed_)) MyStruct
{
SomeOtherStruct x1[MAX_LEN];
uint8_t x2;
} MyStruct;
the definition of the struct in the .c file (value insertion is in some other place in the code):
MyStruct my_cfg;
What i did was compiling the file and creating a dll file, and then wrote to next python lines:
class my_struct(ctypes.Structure):
fields = (
("x1",ctypes.struct),
("x2",ctypes.c_uint32))
def _repr_(self) -> str:
return super()._repr_()
def main():
host_dll = ctypes.CDLL('path-to-dll')
strct = my_struct.in_dll(host_dll,'my_cfg')
After these lines i was able to access the struct fields using the variable 'strct' as i wanted. But, i don't want to define the fields 2 times like i do now - one time in the .h file and a second time in the .py file in the 'my_struct' class.
How can i get the names of the struct's fields? Is there a way to do it using the ctypes library? Or do i have to access the .h from the python script and parse it myself? if so, is there a parser for c struct in python?
I didn't find something like this in my online search.
Also, I would like to hear other ways to access and change a C struct from a python file is someone knows a better way.