}
pres = PyEval_CallObject(pmeth, pargs); / call method(x,y) /
Py_DECREF(pmeth);
Py_DECREF(pargs);
if (pres == NULL)
error("Error calling klass.method");
if (!PyArg_Parse(pres, "s", &cstr)) / convert to C /
error("Can't convert klass.method result");
printf("%s\n", cstr);
Py_DECREF(pres);
}
These 53 lines of C code (not counting its makefile) achieve the same results as the
4 lines of interactive Python we ran earlier—not exactly a stellar result from a developer
productivity perspective! Nevertheless, the model it uses allows C and C++ to leverage
Python in the same way that Python can employ C and C++. As I’ll discuss in this
book’s conclusion in a moment, such combinations can often be more powerful than
their individual parts.
Other Integration Topics
In this chapter, the term integration has largely meant mixing Python with components
written in C or C++ (or other C-compatible languages) in extending and embedding
modes. But from a broader perspective, integration also includes any other technology
that lets us mix Python components into larger, heterogeneous systems. To wrap up
this chapter, this last section briefly summarizes a handful of commonly used integra-
tion technologies beyond the C API tools we’ve explored.
Jython: Java integration
We first met Jython in Chapter 12 and it was discussed earlier in this chapter in
the context of extending. Really, though, Jython is a broader integration platform.
Jython compiles Python code to Java bytecode for execution on the JVM. The
resulting Java-based system directly supports two kinds of integration:
- Extending: Jython uses Java’s reflection API to allow Python programs to call
out to Java class libraries automatically. The Java reflection API provides Java
type information at runtime and serves the same purpose as the glue code we’ve
generated to plug C libraries into Python in this part of the book. In Jython,
however, this runtime type information allows largely automated resolution of
Java calls in Python scripts—no glue code has to be written or generated. - Embedding: Jython also provides a Java PythonInterpreter class API that allows
Java programs to run Python code in a namespace, much like the C API tools
we’ve used to run Python code strings from C programs. In addition, because
Jython implements all Python objects as instances of a Java PyObject class, it is
straightforward for the Java layer that encloses embedded Python code to proc-
ess Python objects.
1538 | Chapter 20: Python/C Integration