Peter
Peter

Reputation: 7334

How to access a Python global variable from 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.

Upvotes: 9

Views: 8299

Answers (4)

Sherm Pendley
Sherm Pendley

Reputation: 13622

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);

Upvotes: 15

Praxeolitic
Praxeolitic

Reputation: 24089

For anyone coming here from Google, here's the 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 accessed as a dictionary.

Upvotes: 6

orip
orip

Reputation: 75477

Are you willing to modify the API a little bit?

  • You can make the C function return the new value for the global, and then call it like this:

    my_global = my_c_func(...)

  • If you're using Robin or the Python C API directly, you can pass the globals dictionary as an additional parameter and modify it

  • If your global is always in the same module, Sherm's solution looks great

Upvotes: 0

Alex Coventry
Alex Coventry

Reputation: 70947

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

Otherwise, much depends on the type of values you're trying to transmit.

Upvotes: -1

Related Questions