O'Reilly logo

Programming Python, 3rd Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A C Extension Module String Stack

Let's kick it up another notch—the following C extension module implements a stack of strings for use in Python scripts. Example 22-15 demonstrates additional API calls, but it also serves as a basis of comparison. It is roughly equivalent to the Python stack module we coded earlier in Chapter 20, but it stacks only strings (not arbitrary objects), has limited string storage and stack lengths, and is written in C.

Alas, the last point makes for a complicated program listing—C code is never quite as nice to look at as equivalent Python code. C must declare variables, manage memory, implement data structures, and include lots of extra syntax. Unless you're a big fan of C, you should focus on the Python interface code in this file, not on the internals of its functions.

Example 22-15. PP3E\Integrate\Extend\Stacks\stackmod.c

/***************************************************** * stackmod.c: a shared stack of character-strings; * a C extension module for use in Python programs; * linked into Python libraries or loaded on import; *****************************************************/ #include "Python.h" /* Python header files */ #include <stdio.h> /* C header files */ #include <string.h> static PyObject *ErrorObject; /* locally raised exception */ #define onError(message) \ { PyErr_SetString(ErrorObject, message); return NULL; } /****************************************************************************** * LOCAL LOGIC/DATA (THE STACK) ******************************************************************************/ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required