num.display() # num saves the C++ 'this' pointer
num.sub(2)
num.display()res = num.square() # converted C++ int return value
print('square: ', res)num.data = 99 # set C++ data member, generated __setattr__
val = num.data # get C++ data member, generated __getattr__
print('data: ', val) # returns a normal Python integer object
print('data+1: ', val + 1)num.display()
print(num) # runs repr in shadow/proxy class
del num # runs C++ destructor automaticallyBecause the C++ class and its wrappers are automatically loaded when imported by
the number.py shadow class module, you run this script like any other:
.../PP4E/Integrate/Extend/Swig/Shadow$ python main.py
Number: 1
add 4
Number=5
sub 2
Number=3
square: 9
data: 99
data+1: 100
Number=99
<number.Number; proxy of <Swig Object of type 'Number *' at 0x7ff4bb48> >
~Number: 99
Much of this output is coming from the C++ class’s methods and is largely the same
as the main.cxx r e s u l t s s h o w n i n Example 20-16 (less the instance output format—it’s
a Python shadow class instance now).Using the low-level extension module
SWIG implements integrations as a C++/Python combination, but you can always use
the generated accessor functions module if you want to, as in Example 20-20. This
version runs the C++ extension module directly without the shadow class, to demon-
strate how the shadow class maps calls back to C++.Example 20-20. PP4E\Integrate\Extend\Swig\Shadow\main_low.py
"""
run similar tests to main.cxx and main.py
but use low-level C accessor function interface
"""from _number import * # c++ extension module wrappernum = new_Number(1)
Number_add(num, 4) # pass C++ 'this' pointer explicitly1508 | Chapter 20: Python/C IntegrationDo
wnload from Wow! eBook <www.wowebook.com>