C API (embedded Python): How to get and set named variables

Farshid Lashkari no at spam.com
Mon Sep 10 14:47:40 EDT 2007


mrabens at gmail.com wrote:
>>From the C API (I'm using Python embedded), how can I get and set the
> value of named variables?  Right now, I'm using hacks like
> PyRun_SimpleString("foobar = 12\n"), but I'd really like to access the
> named objects directly.
> 

You can use the following C functions to set/get named attributes of an 
object:

PyObject_SetAttrString
PyObject_GetAttrString

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

You will probably want to add some error checking in your code.

-Farshid



More information about the Python-list mailing list