Wrapping C++ Classes with SWIG

One of the neater tricks SWIG can perform is class wrapper generation -- given a C++ class declaration and special command-line settings, SWIG generates:

  • A C++ coded Python extension module with accessor functions that interface with the C++ class’s methods and members

  • A Python coded wrapper class (called a “shadow” class in SWIG-speak) that interfaces with the C++ class accessor functions module

As before, simply run SWIG in your makefile to scan the C++ class declaration and compile its outputs. The end result is that by importing the shadow class in your Python scripts, you can utilize C++ classes as though they were really coded in Python. Not only can Python programs make and use instances of the C++ class, they can also customize it by subclassing the generated shadow class.

A Little C++ Class (But Not Too Much)

To see how this all works, we need a C++ class. To illustrate, let’s code a simple one to be used in Python scripts.[149] The following C++ files define a Number class with three methods (add, sub, display), a data member (data), and a constructor and destructor. Example 19-19 shows the header file.

Example 19-19. PP2E\Integrate\Extend\Swig\Shadow\number.h

class Number
{
public:
    Number(int start);
    ~Number(  );
    void add(int value);
    void sub(int value);
    void display(  );
    int data;
};

And Example 19-20 is the C++ class’s implementation file; each method prints a message when called to trace class operations.

Example 19-20. PP2E\Integrate\Extend\Swig\Shadow\number.cxx ...

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.