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

M

mrabens

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.
 
F

Farshid Lashkari

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
 
M

Martoon

Thank you! Just what I needed.

I came across the PyObject_*AttrString() functions earlier when
searching through the docs, and I thought I was in the right area, but
I didn't know what object I was supposed to set the attribute for.
Now I see that it's a module object. It all makes sense now. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top