Retrieve a variable from an embedded interpreter

Mike Johnson afp_randjohnson at yahoo.com
Sun Feb 24 10:03:23 EST 2002


Hello all (who apparently don't read on the weekends):

I've got something that works now. I would just like to say the faq on
the subject is completely not useful. The section, "How do I extract C
values from a Python object?" doesn't address how to get an arbitrary
variable from Python.

Specifically, this guy's comments should be bronzed somewhere:

http://groups.google.com/groups?q=python+set+variable+c&start=30&hl=en&selm=m0wNSjb-001CneC%40shell.rmi.net&rnum=32

I'd like to add a faq item, just after 5.7, to compile together the
concepts addressed in the preceding sections.

---

In order to share values between C and python, it is useful to create
a module. From C one can add methods and variables to the module, and
in Python one can access and change these variables.

In this example, the module's name is "cpserve". It's a simple text
file that includes these statements:
----
#!/usr/bin/python2.1
version = .1
----

>From C, we're going to add a property "a". First, import the module in
C, using Python's API access:
----
PyObject *a;
char *sa;
PyObject *pdict;
PyObject *pymod;

Py_Initialize ();

pdict = PyDict_New();
PyDict_SetItemString( pdict, "__builtins__", PyEval_GetBuiltins() );
pymod = PyImport_ImportModule ( "cpserve" );
----

Next, we'll add the property "a" and set it's value to the string
"hello":
----
a = PyString_FromString ( "hello" );
PyObject_SetAttrString ( pymod, "a", a );
----

Now we're ready to execute the Python code. Here I use
PyRun_SimpleString() but these calls could easily be placed in a file
and executed that way.
----
PyRun_SimpleString ( "import cpserve" );
PyRun_SimpleString ( "print\"a=\" + cpserve.a" );
PyRun_SimpleString ( "cpserve.a = \"hi\"" );
PyRun_SimpleString ( "print \"a=\" + str(cpserve.version)" );

Finally, we can retrieve the value of "cpserve.a" with a C variable:
----
a = PyObject_GetAttrString ( pymod, "a" );
PyArg_Parse ( a, "s", &sa);
printf ( "sa = %s\n", sa );

Py_DECREF ( pdict );
Py_DECREF ( pymod );
Py_DECREF ( a );
Py_Finalize ();
----

When compiled and run, this produces the output:
----
a=hello a=0.1 sa = hi
----

I'm sure somebody will find something wrong with this. Suggestions
are welcome. I'd just like to see some more documentation on
this sort of thing.

And I'm willing to document as I learn. :-)

Thanks,

Mike Johnson




More information about the Python-list mailing list