c++boost.gif (8819 bytes)

A Simple Example

Suppose we have the following C++ API which we want to expose in Python:

#include <string>

namespace hello {
  class world
  {
   public:
      world(int);
      ~world();
      std::string greet() const { return "hi, world"; }
    ...
  };
  std::size_t length(const world& x) { return std::strlen(x.greet()); }
}

Here is the C++ code for a python module called hello which exposes the API using:

#include <boost/python/class_builder.hpp>
// Python requires an exported function called init<module-name> in every
// extension module. This is where we build the module contents.
extern "C"
#ifdef _WIN32
__declspec(dllexport)
#endif
void inithello()
{
    try
    {
       // create an object representing this extension module
       boost::python::module_builder m("hello");
       // Create the Python type object for our extension class
       boost::python::class_builder<hello::world> world_class(m, "world");
       // Add the __init__ function
       world_class.def(boost::python::constructor<int>());
       // Add a regular member function
       world_class.def(&hello::world::get, "get");
       // Add a regular function to the module
       m.def(hello::length, "length");
    }
    catch(...)
    {
       boost::python::handle_exception();    // Deal with the exception for Python
    }
}
// Win32 DLL boilerplate
#if defined(_WIN32)
#include <windows.h>
extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID)
{
    return 1;
}
#endif // _WIN32

That's it! If we build this shared library and put it on our PYTHONPATH we can now access our C++ class and function from Python.

>>> import hello
>>> hi_world = hello.world(3)
>>> hi_world.greet()
'hi, world'
>>> hello.length(hi_world)
9

We can even make a subclass of hello.world:

>>> class my_subclass(hello.world):
...     def greet(self):
...         return 'hello, world'
...
>>> y = my_subclass(4)
>>> y.greet()
'hello, world'

Pretty cool! You can't do that with an ordinary Python extension type!

>>> hello.length(y)
9

Of course, you may now have a slightly empty feeling in the pit of your little pythonic stomach. Perhaps you feel your subclass deserves to have a length() of 12? If so, read on...

Next: Overridable virtual functions Previous: Comparisons with other systems Up: Top

© Copyright David Abrahams 2000. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.

Updated: Nov 26, 2000