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 19-14 demonstrates additional API calls, but also serves as a basis of comparison. It is roughly equivalent to the Python stack module we met earlier in Chapter 14 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 the internals of its functions.

Example 19-14. PP2E\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) ******************************************************************************/ ...

Get Programming Python, Second 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.