I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?
I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.
A global variable in Python is often declared as the top of the program. In other words, variables that are declared outside of a function are known as global variables. You can access global variables in Python both inside and outside the function.
The C language allows the redeclaration of the global variable. It means that this variable can get declared again when the first declaration doesn't lead to the initialization of the variable. It is possible because the second program works pretty well in the C language even if the first one fails during compilation.
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
Global variables can be used by everyone, both inside of functions and outside.
I'm not a python guru, but I found this question interesting so I googled around. This was the first hit on "python embedding API" - does it help?
If the attributes belong to the global scope of a module, then you can use "PyImport_AddModule" to get a handle to the module object. For example, if you wanted to get the value of an integer in the main module named "foobar", you would do the following:
PyObject *m = PyImport_AddModule("__main__"); PyObject *v = PyObject_GetAttrString(m,"foobar"); int foobar = PyInt_AsLong(v); Py_DECREF(v);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With