Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Python global variable from C?

Tags:

python

c

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.

like image 922
Peter Avatar asked Nov 12 '08 21:11

Peter


People also ask

Can you access global variables in Python?

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.

Can you declare global variables in C?

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.

How do you access a variable with a global statement?

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.

Can I call global variable in function Python?

Global variables can be used by everyone, both inside of functions and outside.


1 Answers

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);
like image 60
Sherm Pendley Avatar answered Sep 22 '22 14:09

Sherm Pendley