I am trying to learn how to use the Python/C API correctly - all I actually need to do is to read a global variable (in my case dictionary - but I\'m starting with a simple
I know this question is from long ago, but this is for others who stumble across this while googling.
OP says his code doesn't work, but ironically, his code worked for me better than other examples.(Thanks, @et_l)
So, the answer - how to access python variables from C - for the OP's code (with the main module code OP wrote);
#include
#include
int main () {
Py_Initialize();
PyRun_SimpleString("var1 = 1");
PyRun_SimpleString("var2 = ['bla', 'blalba']");
PyRun_SimpleString("var3 = {'3' : 'Three', '2' : 'Two', '1' : 'One', '0' : 'Ignition!'}");
PyRun_SimpleString("print('end of file - tryStuff!!')");
PyObject *mainModule = PyImport_AddModule("__main__");
PyObject *var1Py = PyObject_GetAttrString(mainModule, "var1");
int c_var1 = PyLong_AsLong(var1Py);
printf("var1 with C: %d\n", c_var1);
Py_Finalize();
return 0;
}