9

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.

1
  • I think what you meant by global variable is only the __main__ module's global variable. Actually each imported python module has its own global variables. Builtin function globals Commented Aug 16, 2018 at 5:35

4 Answers 4

15

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);
Sign up to request clarification or add additional context in comments.

3 Comments

'This' link is broken- anybody have a fixed link?
Fixed it - Odd that they would rearrange the list archives like that, but googling for the quoted text found the message easily enough. :-)
Aaand its broken again
6

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.

Comments

0

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

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.