C API: Getting PyObject by name

P

pbienst

Hi,

I'm embedding Python in a C app.

Say I do the following:

PyRun_SimpleString("a = 1")

Is there then a way to get access to the PyObject corresponding to a,
only making use in C of the fact that it's called "a"?

I've searched through the API docs, but I couldn't really find what I
was looking for.

Any help most appreciated!

Peter
 
T

Thomas Jollans

Hi,

I'm embedding Python in a C app.

Say I do the following:

PyRun_SimpleString("a = 1")

Is there then a way to get access to the PyObject corresponding to a,
only making use in C of the fact that it's called "a"?

I've searched through the API docs, but I couldn't really find what I
was looking for.

No. Not as such. But you could use PyRun_String, or PyRun_StringFlags. You
could then access the globals object, but I ask you, why would you want to
bind the object to a name in the first place? Use the fact that PyRun_String
returns a reference to the result of an expression!
 
P

pbienst

Here is what I tried, but it prints out '-1':

PyObject* obj = PyRun_String("1", Py_single_input,
PyEval_GetGlobals(), PyEval_GetLocals());
long d = PyLong_AsLong(obj);
printf("long:%ld\n", d);
Py_DECREF(obj);

Peter
 
P

pbienst

For reference to posterity, this is how I got it to work in the end:

PyObject* module = PyImport_ImportModule("__builtin__");
PyObject* obj = PyRun_String("1", Py_eval_input,
PyModule_GetDict(module), NULL);
Py_DECREF(module);
long d = PyLong_AsLong(obj);
printf("long:%ld\n", d);
Py_DECREF(obj);

Can't say I really understand it, though, all rather esoteric...

Peter
 

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

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top