how to use PyRun_String
Dave Kuhlman
dkuhlman at rexx.com
Thu Aug 1 13:51:06 EDT 2002
vb wrote:
> after a PyRun_SimpleString("s='a string'");
> how can I get s as a C PyObject*?
> I tried PyRun_String but I dont know what to pass in last 2
> params.(globals & locals dictionary) so it returns NULL.
>
> Thanks.
The script you are running sets a global variable. You want to get
the globals dictionary and extract that variable from it.
Something like the following should work:
/* ============================================================= */
PyObject * module;
PyObject * dict;
PyObject * obj;
long lval;
PyRun_SimpleString("obj = 3 * 5");
module = PyImport_AddModule("__main__");
dict = PyModule_GetDict(module);
obj = PyMapping_GetItemString(dict, "obj");
if (obj != NULL)
{
lval = PyInt_AsLong(obj);
printf("obj: %d\n", lval);
}
else
{
printf("Object not found\n");
} /* if */
/* ============================================================= */
But, I don't know whether this is the "approved" way to do it. I
had to look at the implementation of PyRun_SimpleStringFlags() in
Python-2.2.1/Python/pythonrun.c in order to learn how to "peek
inside the machine" and get the global dictionary. Can someone
comment on whether this is an appropriate way to do that?
- Dave
--
Dave Kuhlman
dkuhlman at rexx.com
http://www.rexx.com/~dkuhlman
More information about the Python-list
mailing list