A C Extension Type String Stack
So far in this chapter, we’ve been dealing with C extension modules—flat function libraries. To implement multiple-instance objects in C, you need to code a C extension type, not a module. Like Python classes, C types generate multiple-instance objects and can overload (i.e., intercept and implement) Python expression operators and type operations. In recent Python releases, C types can also support subclassing just like Python classes.
One of the biggest drawbacks of types, though, is their size—to implement a realistically equipped C type, you need to code lots of not-very-pretty C code and fill out type descriptor tables with pointers to link up operation handlers. In fact, C extension types are so complex that I’m going to cut some details here. To give you a feel for the overall structure, Example 22-16 presents a C string stack type implementation, but with the bodies of all its functions stripped out. For the complete implementation, see this file in the book’s examples distribution.
This C type roughly implements the same interface as the stack
classes we met in Chapter 20,
but it imposes a few limits on the stack itself. The stripped parts
use the same algorithms as the C module in Example 22-15, but they operate
on the passed-in self object, which
now refers to the particular type instance object being processed,
just as the first argument does in class methods. In types, self is a pointer to an allocated C struct that represents a type instance ...