I statically declared a large structure in C, but I need to use the same data to do some analysis in Python. I would prefer not to replicate this data in Python to avoid errors, is there a way (read-only) to access the data directly in Python? I looked at "ctypes" and SWIG, and none of them seem to provide what I'm looking for ...
For example, I have:
/*.h file * /
typedef struct { double data[10]; } NestedStruct; typedef struct { NestedStruct array[10]; } MyStruct;
/*.c file * /
MyStruct the_data_i_want = { {0}, { {1,2,3,4} }, {0}, };
Ideally, I would like something that would allow me to get this in python and access it through the_data_i_want.array[1].data[2] or something like that. Any thoughts? I got swig to βworkβ in the sense that I was able to compile / import the .so created from my .c file, but I could not access it through cvars. Maybe there is another way? It seems to be so hard ....
Actually, I realized that. I add this because my reputation does not allow me to answer my question within 8 hours, and since I do not want to remember after 8 hours, I will add it now. I am sure there is a good reason for this that I do not understand.
Figured it out.
1st I compiled my .c file to a library:
Then I used types to define a python class that stores data:
from ctypes import * class NestedStruct(Structure): _fields_ = [("data", c_double*10)] class MyStruct(Structure): _fields_ = [("array", NestedStruct*10)]
Then I loaded the shared library in python:
my_lib = cdll.LoadLibrary("my_lib.so")
Then I used the in_dll method to get the data:
the_data_i_want = MyStruct.in_dll(my_lib, "the_data_i_want")
Then I could access it as if it were C. the_data_i_want.array[1].data[2]
Note. Maybe I messed up the syntax a bit because my actual data structure is nested 3 levels and I wanted to simplify it here for illustration.