Py_BuildValue
Converts C values to Python objects
We used both of the data conversion functions earlier in this chapter in extension
modules. The PyEval_CallObject call in this version of the example is the key point
here: it runs the imported function with a tuple of arguments, much like the Python
func(args) call syntax. The Python function’s return value comes back to C as a
PyObject, a generic Python object pointer.
Example 20-27. PP4E\Integrate\Embed\Basics\embed-object.c
/ fetch and call objects in modules /
#include <Python.h>
main() {
char cstr;
PyObject pstr, pmod, pfunc, *pargs;
printf("embed-object\n");
Py_Initialize();
/ get usermod.message /
pmod = PyImport_ImportModule("usermod");
pstr = PyObject_GetAttrString(pmod, "message");
/ convert string to C /
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
Py_DECREF(pstr);
/ call usermod.transform(usermod.message) /
pfunc = PyObject_GetAttrString(pmod, "transform");
pargs = Py_BuildValue("(s)", cstr);
pstr = PyEval_CallObject(pfunc, pargs);
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);
/ free owned objects /
Py_DECREF(pmod);
Py_DECREF(pstr);
Py_DECREF(pfunc); / not really needed in main() /
Py_DECREF(pargs); / since all memory goes away /
Py_Finalize();
}
When compiled and run, the result is the same again:
.../PP4E/Integrate/Embed/Basics$ ./embed-object
embed-object
The meaning of life...
THE MEANING OF PYTHON...
However, this output is generated by C this time—first, by fetching the Python mod-
ule’s message attribute value, and then by fetching and calling the module’s transform
Basic Embedding Techniques | 1525