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

Wrapping C++ Classes with SWIG

One of the more clever tricks SWIG can perform is class wrapper generation. Given a C++ class declaration and special command-line settings, SWIG generates the following:

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

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

As before, to use SWIG in this domain, write and debug your class as though it would be used only from C++. Then, simply run SWIG in your makefile to scan the C++ class declaration and compile and link its output. 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 Simple C++ Extension Class

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

Example 22-18. PP3E\Integrate\Extend\Swig\Shadow\number.h

class Number { public: Number(int start); // constructor ~Number( ); // destructor void add(int value); // update data member void sub(int value); int square( ...

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