[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

As we did earlier, 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 im-
porting 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 in-
stances 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 one to be used in
Python scripts. You have to understand C++ to make sense of this section, of course,
and SWIG supports advanced C++ tools (including templates and overloaded func-
tions and operators), but I’ll keep this example simple for illustration. The following
C++ files define a Number class with four methods (add, sub, square, and display), a data
member (data), and a constructor and destructor. Example 20-14 shows the header file.


Example 20-14. PP4E\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(); // return a value
void display(); // print data member
int data;
};


Example 20-15 is the C++ class’s implementation file; most methods print a message
when called to trace class operations. Notice how this uses printf instead of C++’s
cout; this once resolved an output overlap issue when mixing C++ cout with Python
2.X standard output streams on Cygwin. It’s probably a moot point today—because
Python 3.X’s output system and buffering might mix with C++’s arbitrarily, C++
should generally flush the output stream (with fflush(stdout) or cout<<flush) if it
prints intermixed text that doesn’t end in a newline. Obscure but true when disparate
language systems are mixed.


Example 20-15. PP4E\Integrate\Extend\Swig\Shadow\number.cxx


///////////////////////////////////////////////////////////////
// implement a C++ class, to be used from Python code or not;
// caveat: cout and print usually both work, but I ran into a
// c++/py output overlap issue on Cygwin that prompted printf
///////////////////////////////////////////////////////////////


#include "number.h"
#include "stdio.h" // versus #include "iostream.h"


Wrapping C++ Classes with SWIG | 1503
Free download pdf