// Tell Python to take ownership of factory's result
def("factory", factory,
return_value_policy<manage_new_object>());
[endsect]
[section Class Virtual Functions]
In this section, we will learn how to make functions behave polymorphically
through virtual functions. Continuing our example, let us add a virtual function
to our [^Base] class:
struct Base
{
virtual ~Base() {}
virtual int f() = 0;
};
One of the goals of Boost.Python is to be minimally intrusive on an existing C++
design. In principle, it should be possible to expose the interface for a 3rd
party library without changing it. It is not ideal to add anything to our class
`Base`. Yet, when you have a virtual function that's going to be overridden in
Python and called polymorphically *from C++*, we'll need to add some
scaffoldings to make things work properly. What we'll do is write a class
wrapper that derives from `Base` that will unintrusively hook into the virtual
functions so that a Python override may be called:
struct BaseWrap : Base, wrapper<Base>
{
int f()
{
return this->get_override("f")();
}
};
Notice too that in addition to inheriting from `Base`, we also multiply-
inherited `wrapper<Base>` (See [@../reference/high_level_components/boost_python_wrapper_hpp.html#high_level_components.boost_python_wrapper_hpp.class_template_wrapper Wrapper]). The
`wrapper` template makes the job of wrapping classes that are meant to
overridden in Python, easier.
[blurb __alert__ [*MSVC6/7 Workaround]
If you are using Microsoft Visual C++ 6 or 7, you have to write `f` as:
BaseWrap's overridden virtual member function `f` in effect calls the
corresponding method of the Python object through `get_override`.
Finally, exposing `Base`:
class_<BaseWrap, boost::noncopyable>("Base")
.def("f", pure_virtual(&Base::f))
;
`pure_virtual` signals Boost.Python that the function `f` is a pure virtual
function.
[note [*member function and methods]
Python, like many object oriented languages uses the term [*methods].
Methods correspond roughly to C++'s [*member functions]]
[endsect]
[section Virtual Functions with Default Implementations]
We've seen in the previous section how classes with pure virtual functions are
wrapped using Boost.Python's [@../reference/high_level_components/boost_python_wrapper_hpp.html#high_level_components.boost_python_wrapper_hpp.class_template_wrapper class wrapper]
facilities. If we wish to wrap [*non]-pure-virtual functions instead, the
mechanism is a bit different.
Recall that in the [link tutorial.exposing.class_virtual_functions previous section], we
wrapped a class with a pure virtual function that we then implemented in C++, or
Python classes derived from it. Our base class:
struct Base
{
virtual int f() = 0;
};
had a pure virtual function [^f]. If, however, its member function [^f] was
not declared as pure virtual:
struct Base
{
virtual ~Base() {}
virtual int f() { return 0; }
};
We wrap it this way:
struct BaseWrap : Base, wrapper<Base>
{
int f()
{
if (override f = this->get_override("f"))
return f(); // *note*
return Base::f();
}
int default_f() { return this->Base::f(); }
};
Notice how we implemented `BaseWrap::f`. Now, we have to check if there is an
override for `f`. If none, then we call `Base::f()`.
[blurb __alert__ [*MSVC6/7 Workaround]
If you are using Microsoft Visual C++ 6 or 7, you have to rewrite the line
with the `*note*` as:
`return call<char const*>(f.ptr());`.]
Finally, exposing:
class_<BaseWrap, boost::noncopyable>("Base")
.def("f", &Base::f, &BaseWrap::default_f)
;
Take note that we expose both `&Base::f` and `&BaseWrap::default_f`.
Boost.Python needs to keep track of 1) the dispatch function [^f] and 2) the
forwarding function to its default implementation [^default_f]. There's a
special [^def] function for this purpose.
In Python, the results would be as expected:
[python]
>>> base = Base()
>>> class Derived(Base):
... def f(self):
... return 42
...
>>> derived = Derived()
Calling [^base.f()]:
>>> base.f()
0
Calling [^derived.f()]:
>>> derived.f()
42
[endsect]
[section Class Operators/Special Functions]
[h2 Python Operators]
C is well known for the abundance of operators. C++ extends this to the
extremes by allowing operator overloading. Boost.Python takes advantage of
this and makes it easy to wrap C++ operator-powered classes.
Consider a file position class [^FilePos] and a set of operators that take
on FilePos instances:
[c++]
class FilePos { /*...*/ };
FilePos operator+(FilePos, int);
FilePos operator+(int, FilePos);
int operator-(FilePos, FilePos);
FilePos operator-(FilePos, int);
FilePos& operator+=(FilePos&, int);
FilePos& operator-=(FilePos&, int);
bool operator<(FilePos, FilePos);
The class and the various operators can be mapped to Python rather easily
and intuitively:
class_<FilePos>("FilePos")
.def(self + int()) // __add__
.def(int() + self) // __radd__
.def(self - self) // __sub__
.def(self - int()) // __sub__
.def(self += int()) // __iadd__
.def(self -= other<int>())
.def(self < self); // __lt__
The code snippet above is very clear and needs almost no explanation at
all. It is virtually the same as the operators' signatures. Just take
note that [^self] refers to FilePos object. Also, not every class [^T] that
you might need to interact with in an operator expression is (cheaply)
default-constructible. You can use [^other<T>()] in place of an actual
[^T] instance when writing "self expressions".
[h2 Special Methods]
Python has a few more ['Special Methods]. Boost.Python supports all of the
standard special method names supported by real Python class instances. A
similar set of intuitive interfaces can also be used to wrap C++ functions
that correspond to these Python ['special functions]. Example:
class Rational
{ public: operator double() const; };
Rational pow(Rational, Rational);
Rational abs(Rational);
ostream& operator<<(ostream&,Rational);
class_<Rational>("Rational")
.def(float_(self)) // __float__
.def(pow(self, other<Rational>)) // __pow__
.def(abs(self)) // __abs__
.def(str(self)) // __str__
;
Need we say more?
[note What is the business of `operator<<`?
Well, the method `str` requires the `operator<<` to do its work (i.e.
`operator<<` is used by the method defined by `def(str(self))`.]
[endsect]
[endsect] [/ Exposing Classes ]
[section Functions]
In this chapter, we'll look at Boost.Python powered functions in closer
detail. We will see some facilities to make exposing C++ functions to
Python safe from potential pifalls such as dangling pointers and
references. We will also see facilities that will make it even easier for
us to expose C++ functions that take advantage of C++ features such as
overloading and default arguments.
[:['Read on...]]
But before you do, you might want to fire up Python 2.2 or later and type
[^>>> import this].
[pre
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
]
[section Call Policies]
In C++, we often deal with arguments and return types such as pointers
and references. Such primitive types are rather, ummmm, low level and
they really don't tell us much. At the very least, we don't know the
owner of the pointer or the referenced object. No wonder languages
such as Java and Python never deal with such low level entities. In
C++, it's usually considered a good practice to use smart pointers
which exactly describe ownership semantics. Still, even good C++
interfaces use raw references and pointers sometimes, so Boost.Python
must deal with them. To do this, it may need your help. Consider the
following C++ function:
X& f(Y& y, Z* z);
How should the library wrap this function? A naive approach builds a
Python X object around result reference. This strategy might or might
not work out. Here's an example where it didn't
>>> x = f(y, z) # x refers to some C++ X
>>> del y
>>> x.some_method() # CRASH!
What's the problem?
Well, what if f() was implemented as shown below:
X& f(Y& y, Z* z)
{
y.z = z;
return y.x;
}
The problem is that the lifetime of result X& is tied to the lifetime
of y, because the f() returns a reference to a member of the y
object. This idiom is is not uncommon and perfectly acceptable in the
context of C++. However, Python users should not be able to crash the
system just by using our C++ interface. In this case deleting y will
invalidate the reference to X. We have a dangling reference.
Here's what's happening:
# [^f] is called passing in a reference to [^y] and a pointer to [^z]
# A reference to [^y.x] is returned
# [^y] is deleted. [^x] is a dangling reference
# [^x.some_method()] is called
# [*BOOM!]
We could copy result into a new object:
[python]
>>> f(y, z).set(42) # Result disappears
>>> y.x.get() # No crash, but still bad
3.14
This is not really our intent of our C++ interface. We've broken our
promise that the Python interface should reflect the C++ interface as
closely as possible.
Our problems do not end there. Suppose Y is implemented as follows:
[c++]
struct Y
{
X x; Z* z;
int z_value() { return z->value(); }
};
Notice that the data member [^z] is held by class Y using a raw
pointer. Now we have a potential dangling pointer problem inside Y:
>>> x = f(y, z) # y refers to z
>>> del z # Kill the z object
>>> y.z_value() # CRASH!
For reference, here's the implementation of [^f] again:
X& f(Y& y, Z* z)
{
y.z = z;
return y.x;
}
Here's what's happening:
# [^f] is called passing in a reference to [^y] and a pointer to [^z]
# A pointer to [^z] is held by [^y]
# A reference to [^y.x] is returned
# [^z] is deleted. [^y.z] is a dangling pointer
# [^y.z_value()] is called
# [^z->value()] is called
# [*BOOM!]
[h2 Call Policies]
Call Policies may be used in situations such as the example detailed above.
In our example, [^return_internal_reference] and [^with_custodian_and_ward]
are our friends:
def("f", f,
return_internal_reference<1,
with_custodian_and_ward<1, 2> >());
What are the [^1] and [^2] parameters, you ask?
return_internal_reference<1
Informs Boost.Python that the first argument, in our case [^Y& y], is the
owner of the returned reference: [^X&]. The "[^1]" simply specifies the
first argument. In short: "return an internal reference [^X&] owned by the
1st argument [^Y& y]".
with_custodian_and_ward<1, 2>
Informs Boost.Python that the lifetime of the argument indicated by ward
(i.e. the 2nd argument: [^Z* z]) is dependent on the lifetime of the
argument indicated by custodian (i.e. the 1st argument: [^Y& y]).
It is also important to note that we have defined two policies above. Two
or more policies can be composed by chaining. Here's the general syntax:
policy1<args...,
policy2<args...,
policy3<args...> > >
Here is the list of predefined call policies. A complete reference detailing
these can be found [@../reference/function_invocation_and_creation/models_of_callpolicies.html here].
* [*with_custodian_and_ward]: Ties lifetimes of the arguments
* [*with_custodian_and_ward_postcall]: Ties lifetimes of the arguments and results
* [*return_internal_reference]: Ties lifetime of one argument to that of result
See the [@../reference/function_invocation_and_creation/boost_python_overloads_hpp.html#function_invocation_and_creation.boost_python_overloads_hpp.macros overloads reference]
for details.
[h2 init and optional]
A similar facility is provided for class constructors, again, with
default arguments or a sequence of overloads. Remember [^init<...>]? For example,
given a class X with a constructor:
struct X
{
X(int a, char b = 'D', std::string c = "constructor", double d = 0.0);
/*...*/
}
You can easily add this constructor to Boost.Python in one shot: