Download SWIG Manual

Transcript
SWIG Users Guide
SWIG and Python
168
Python shadow classes
The low-level interface generated by SWIG provides access to C structures and C++ classes, but
it doesn’t look much like a class that might be created in Python. However, it is possible to use
the low-level C interface to write a Python class that looks like the original C++ class. In this case,
the Python class is said to “shadow” the C++ class. That is, it behaves like the original class, but
is really just a wrapper around a C++ class.
A simple example
For our earlier List class, a Python shadow class could be written by hand like this :
class List:
def __init__(self):
self.this = new_List()
def __del__(self):
delete_List(self.this)
def search(self,item):
return List_search(self.this,item)
def insert(self,item):
List_insert(self.this,item)
def remove(self,item):
List_remove(self.this,item)
def get(self,n):
return List_get(self.this,n)
def __getattr__(self,name):
if name == “length”: return List_length_get(self.this))
else :
return self.__dict__[name]
def __setattr__(self,name,value):
if name == “length”: List_length_set(self.this,value)
else :
self.__dict__[name] = value
When used in a Python script, we can use the class as follows :
>>> l = List()
>>> l.insert(“Ale”)
>>> l.insert(“Stout”)
>>> l.insert(“Lager”)
>>> List_print(l.this)
Lager
Stout
Ale
>>> l.length
3
Obviously, this is a much nicer interface than before--and it only required a small amount of
Python coding.
Why write shadow classes in Python?
While one could wrap C/C++ objects directly into Python as new Python types, this approach
has a number of problems. First, as the C/C++ code gets complicated, the resulting wrapper
code starts to become extremely ugly. It also becomes hard to handle inheritance and more
advanced language features. A second, and more serious problem, is that Python “types” created
Version 1.1, June 24, 1997