C-coded operations with the Python interpreter as C function pointers. In all cases, the
C layer is responsible for converting arguments passed from Python to C form and for
converting results from C to Python form. Python scripts simply import C extensions
and use them as though they were really coded in Python. Because C code does all the
translation work, the interface is very seamless and simple in Python scripts.
C modules and types are also responsible for communicating errors back to Python,
detecting errors raised by Python API calls, and managing garbage-collector reference
counters on objects retained by the C layer indefinitely—Python objects held by your
C code won’t be garbage-collected as long as you make sure their reference counts don’t
fall to zero. Once coded, C modules and types may be linked to Python either statically
(by rebuilding Python) or dynamically (when first imported). Thereafter, the C exten-
sion becomes another toolkit available for use in Python scripts.
A Simple C Extension Module
At least that’s the short story; C modules require C code, and C types require more of
it than we can reasonably present in this chapter. Although this book can’t teach you
C development skills if you don’t already have them, we need to turn to some code to
make this domain more concrete. Because C modules are simpler, and because C types
generally export a C module with an instance constructor function, let’s start off by
exploring the basics of C module coding with a quick example.
As mentioned, when you add new or existing C components to Python in the traditional
integration model, you need to code an interface (“glue”) logic layer in C that handles
cross-language dispatching and data translation. The C source file in Example 20-1
shows how to code one by hand. It implements a simple C extension module named
hello for use in Python scripts, with a function named message that simply returns its
input string argument with extra text prepended. Python scripts will call this function
as usual, but this one is coded in C, not in Python.
Example 20-1. PP4E\Integrate\Extend\Hello\hello.c
/****
- A simple C extension module for Python, called "hello"; compile
- this into a ".so" on python path, import and call hello.message;
****/
#include <Python.h>
#include <string.h>
/ module functions /
static PyObject / returns object /
message(PyObject self, PyObject args) / self unused in modules /
{ / args from Python call /
char fromPython, result[1024];
if (! PyArg_Parse(args, "(s)", &fromPython)) / convert Python -> C /
return NULL; / null=raise exception /
A Simple C Extension Module| 1487