This is fairly easy stuff in Python. You can do all of these operations in C, too, but it
takes a bit more code. The C file in Example 20-34 implements these steps by arranging
calls to the appropriate Python API tools.
Example 20-34. PP4E\Integrate\Embed\Pyclass\objects.c
#include <Python.h>
#include <stdio.h>
main() {
/ run objects with low-level calls /
char arg1="sir", arg2="robin", cstr;
PyObject pmod, pclass, pargs, pinst, pmeth, *pres;
/ instance = module.klass() /
Py_Initialize();
pmod = PyImport_ImportModule("module"); / fetch module /
pclass = PyObject_GetAttrString(pmod, "klass"); / fetch module.class /
Py_DECREF(pmod);
pargs = Py_BuildValue("()");
pinst = PyEval_CallObject(pclass, pargs); / call class() /
Py_DECREF(pclass);
Py_DECREF(pargs);
/ result = instance.method(x,y) /
pmeth = PyObject_GetAttrString(pinst, "method"); / fetch bound method /
Py_DECREF(pinst);
pargs = Py_BuildValue("(ss)", arg1, arg2); / convert to Python /
pres = PyEval_CallObject(pmeth, pargs); / call method(x,y) /
Py_DECREF(pmeth);
Py_DECREF(pargs);
PyArg_Parse(pres, "s", &cstr); / convert to C /
printf("%s\n", cstr);
Py_DECREF(pres);
}
Step through this source file for more details; it’s mostly a matter of figuring out how
you would accomplish the task in Python, and then calling equivalent C functions in
the Python API. To build this source into a C executable program, run the makefile in
this file’s directory in the book examples package (it’s analogous to makefiles we’ve
already seen, so we’ll omit it here). After compiling, run it as you would any other C
program:
.../PP4E/Integrate/Embed/Pyclass$ ./objects
brave sir robin
This output might seem anticlimactic, but it actually reflects the return values sent back
to C by the Python class method in file module.py. C did a lot of work to get this little
string—it imported the module, fetched the class, made an instance, and fetched and
called the instance method with a tuple of arguments, performing data conversions and
1536 | Chapter 20: Python/C Integration