Number_display(num) # use accessor functions in the C module
Number_sub(num, 2)
Number_display(num)
print(Number_square(num))
Number_data_set(num, 99)
print(Number_data_get(num))
Number_display(num)
print(num)
delete_Number(num)
This script generates essentially the same output as main.py, but it’s been slightly sim-
plified, and the C++ class instance is something lower level than the proxy class here:
.../PP4E/Integrate/Extend/Swig/Shadow$ python main_low.py
Number: 1
add 4
Number=5
sub 2
Number=3
9
99
Number=99
_6025aa00_p_Number
~Number: 99
Subclassing the C++ class in Python
Using the extension module directly works, but there is no obvious advantage to mov-
ing from the shadow class to functions here. By using the shadow class, you get both
an object-based interface to C++ and a customizable Python object. For instance, the
Python module shown in Example 20-21 extends the C++ class, adding an extra
print call statement to the C++ add method and defining a brand-new mul method.
Because the shadow class is pure Python, this works naturally.
Example 20-21. PP4E\Integrate\Extend\Swig\Shadow\main_subclass.py
"sublass C++ class in Python (generated shadow class)"
from number import Number # import shadow class
class MyNumber(Number):
def add(self, other): # extend method
print('in Python add...')
Number.add(self, other)
def mul(self, other): # add new method
print('in Python mul...')
self.data = self.data * other
num = MyNumber(1) # same tests as main.cxx, main.py
num.add(4) # using Python subclass of shadow class
num.display() # add() is specialized in Python
num.sub(2)
num.display()
Wrapping C++ Classes with SWIG | 1509