
P1: JYS
app02 JWBK378-Fletcher April 24, 2009 8:20 Printer: Yet to come
212 Financial Modelling in Python
B.4 PYTHON OPERATORS
Boost.Python makes it extremely easy to wrap C++ operator-powered classes. A simple
example should suffice. Consider the class:
class Vector{ /*...*/};
Vector operator+(Vector const&, float);
Vector operator+(float, Vector const&);
Vector operator-(Vector const&, float);
Vector operator-(float, Vector const&);
Vector& operator+=(Vector&, float);
Vector& operator-=(Vector&, float);
bool operator<(Vector const&, Vector const&);
The class and operators can be mapped to Python by writing:
class <Vector>(‘‘Vector’’)
.def(self + float() )
.def(float() + self )
.def(self - float() )
.def(float() - self )
.def(self += float())
.def(self -= float())
.def(self < self)
;
B.5 FUNCTIONS
In C++ it is common to come across functions with arguments and return types that are pointers
or references. The problem with such primitive types is that we don’t know the owner of the
pointer or referenced object. Although most C++ programmers now use smart pointers with
clear ownership semantics, nevertheless there exists a lot of older C++ code with raw pointers.
So Boost.Python has to be able to deal with them. The main issue to solve is the problem of
dangling pointers and references. Let’s consider the following simple C++ function:
X& f(Y& y, Z* z)
{
y.z = z;
return y.x;
}
The above function binds the lifetime ...