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

(yzsuai) #1

cout << "data+1: " << val + 1 << endl;


num->display();
cout << num << endl; // print raw instance ptr
delete num; // run destructor
}


You can use the g++ command-line C++ compiler program to compile and run this
code on Cygwin (it’s the same on Linux). If you don’t use a similar system, you’ll have
to extrapolate; there are far too many C++ compiler differences to list here. Type the
compile command directly or use the cxxtest target in this example directory’s makefile
shown ahead, and then run the purely C++ program created:


.../PP4E/Integrate/Extend/Swig/Shadow$ make -f makefile.number-swig cxxtest
g++ main.cxx number.cxx -Wno-deprecated

.../PP4E/Integrate/Extend/Swig/Shadow$ ./a.exe
Number: 1
add 4
Number=5
sub 2
Number=3
square: 9
data: 99
data+1: 100
Number=99
0xe502c0
~Number: 99

Wrapping the C++ Class with SWIG


But enough C++: let’s get back to Python. To use the C++ Number class of the preceding
section in Python scripts, you need to code or generate a glue logic layer between the
two languages, just as in prior C extension examples. To generate that layer automat-
ically, write a SWIG input file like the one shown in Example 20-17.


Example 20-17. PP4E\Integrate\Extend\Swig\Shadow\number.i


/****



  • Swig module description file for wrapping a C++ class.

  • Generate by running "swig -c++ -python number.i".

  • The C++ module is generated in file number_wrap.cxx;

  • module 'number' refers to the number.py shadow class.
    ****/


%module number


%{
#include "number.h"
%}


%include number.h


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