Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Click here to view the latest version of this page.
Next

Chapter1.python 1.0

Joel de Guzman

David Abrahams

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt )

Table of Contents

QuickStart
Building Hello World
Exposing Classes
Constructors
Class Data Members
Class Properties
Inheritance
Class Virtual Functions
Virtual Functions with Default Implementations
Class Operators/Special Functions
Functions
Call Policies
Overloading
Default Arguments
Auto-Overloading
Object Interface
Basic Interface
Derived Object types
Extracting C++ objects
Enums
Embedding
Using the interpreter
Iterators
Exception Translation
General Techniques
Creating Packages
Extending Wrapped Objects in Python
Reducing Compiling Time

QuickStart

The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).

Hello World

Following C/C++ tradition, let's start with the "hello, world". A C++ Function:

char const* greet()
{
   return "hello, world";
}

can be exposed to Python by writing a Boost.Python wrapper:

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session:

>>> import hello_ext
>>> print hello.greet()
hello, world

Next stop... Building your Hello World module from start to finish...

Last revised: November 22, 2008 at 03:24:11 GMT


Next