Python’s C Extension API
Adding new functionality to Python is straightforward and fairly painless. Python provides an API for just this purpose that defines the types, macros, and external variables and functions needed to allow a Python application to import an extension module written in C and treat it as if it had been written in Python from the outset. The Python API is incorporated into a C source file by including the header file Python.h and then linking the module with the Python libraries.
The intent of this section is to provide an overview of what an extension module looks like and how it is structured, since in this book we will be building most of our extensions by hand. While something like the SWIG tool (available from http://www.swig.org) can help automate the process of creating a C extension module, using the header files for the external module or modules to create (most of) the necessary extension code, most of what we will need extensions for won’t really warrant this approach. SWIG does, however, have some interesting uses, one of which is using Python to test C code. A description of this can be found here: http://www.swig.org/papers/Py96/python96.html.
Extension Source Module Organization
The internal layout of an extension source module typically follows a pattern like the one shown in Figure 5-2.
Figure 5-2. Python extension module internal layout
The primary ...
Get Real World Instrumentation with Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.