Saturday, February 19, 2011

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.

From stackoverflow
  • 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);
    
  • 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.

  • 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

0 comments:

Post a Comment