How to access Python global variable from C?

I have some global variables in a Python script. Some functions in this script call in C - is it possible to set one of these variables in C, and if so, how?

I appreciate that this is not a very nice design, but I need to make a small change to the existing code, I do not want to start large-scale refactoring of existing scripts.

+9
c python
source share
4 answers

I'm not a python guru, but I found this question interesting, so I searched googled. This was the first hit in the "python implementation API" - does it help?

If the attributes belong to the global module volume, then you can use the "PyImport_AddModule" to get a handle to the module object. For example, if you wanted to get an integer value 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); 
+14
source share

For those who come here from Google, here is a direct method:

 PyObject* PyEval_GetGlobals() 

https://docs.python.org/2/c-api/reflection.html

https://docs.python.org/3/c-api/reflection.html

The return value is available as a dictionary.

+5
source share

I recommend using pyrex to create an extension module in which you can store values ​​in python, and cdef a set of functions that can be called from C to return the values ​​there.

Otherwise, a lot depends on the type of values ​​you are trying to pass.

0
source share

Do you want to change the API a bit?

  • You can force the C function to return a new value for the global, and then call it as follows:

    my_global = my_c_func(...)

  • If you use Robin or the Python C API, you can pass the global dictionary as an optional parameter and change it

  • If your global server is always in one module, Sherm solution looks great
0
source share

All Articles