Chapter 17. Extending and Embedding

Introduction

Credit: David Beazley, University of Chicago

One of Python’s most powerful features is its ability to be hooked to libraries and programs written in classic compiled languages such as C, C++, and Fortran. A large number of Python’s built-in library modules are written as extension modules in C so that operating system services, networking functions, databases, and other features can be easily accessed from the interpreter. In addition, a number of application programmers write extensions in order to use Python as a framework for controlling large software packages coded in other languages.

The gory details of how Python interfaces with other languages can be found in various Python programming books, as well as online documentation at www.python.org (directory Demo, distributed as part of the Python source distribution, also contains several useful examples). However, the general approach revolves around the creation of special wrapper functions that hook into the interpreter. For example, if you had a C function like this:

      int gcd(int x, int y) {
          int g = y;
          while (x > 0) {
              g = x;
              x = y % x;
              y = g;
          }
          return g;
      }

and you wanted to access it from Python in a module named spam, you’d write some special wrapper code like this:

 #include "Python.h" extern int gcd(int, int); PyObject *wrap_gcd(PyObject *self, PyObject *args) { int x, y, g; if(!PyArg_ParseTuple(args, "ii", &x, &y)) return NULL; g = gcd(x, y); return Py_BuildValue("i", g); } ...

Get Python Cookbook, 2nd Edition 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.