
P1: JYS
app02 JWBK378-Fletcher April 24, 2009 8:20 Printer: Yet to come
Appendix B
Boost.Python
The Boost.Python library provides a framework for seamlessly wrapping C++ classes, func-
tions and objects to Python, and vice-versa. No special tools are used – just the C++ compiler.
The library has been so designed that you should not have to change the C++ code in order
to wrap it. Through the use of advanced metaprogramming techniques in Boost.Python, the
syntax of the actual wrapping code, has the look of a declarative interface definition language.
In this appendix we introduce the core features of Boost.Python. The sections are loosely
based on the online Getting Started Tutorial in the Boost.Python distribution. For more ex-
haustive documentation, the reader is encouraged to consult the online reference manual at
http://www.boost.org.
B.1 HELLO WORLD
Let’s start with the ‘Hello world’ C++ function
char const* greet()
{
return ‘‘Hello world’’;
}
The function can be exposed to Python by writing the following Boost.Python wrapper:
#include <boost/python.hpp>
BOOST
PYTHON MODULE(hello ext)
{
using namespace boost::python;
def(‘‘greet’’, greet);
}
We can now build this as a shared library and the resulting library is a Python module. An
invocation of the function from the Python command line looks like
>>> import hello ext
>>> print hello
ext.greet()
B.2 CLASSES, CONSTRUCTORS AND METHODS
Let’s consider a C++ class/struct ...