Chapter 16. Extending and Embedding
Introduction
Credit: David Beazley, University of Chicago
One of Python’s most powerful features is its ability to hook to libraries and programs written in compiled languages, such as C, C++, and Fortran. In fact, 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 are writing extensions, which can use Python as a framework for controlling large software packages written in compiled languages.
The gory details of how Python interfaces with other languages can be found in various Python programming books and at http://www.python.org. However, the general approach revolves around the creation of special wrapper functions that hook into the interpreter. For example, say you have a C function such as this:
int gcd(int x, int y) {
int g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}If you want to access it from Python in a spam
module, you’d have to write a 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); } /* List of all functions in the module */ static PyMethodDef spammethods[] = { {"gcd", wrap_gcd, METH_VARARGS }, { NULL, NULL ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access