c++boost.gif (8819 bytes)

A Peek Under the Hood

Declaring a class_builder<T> causes the instantiation of an extension_class<T> to which it forwards all member function calls and which is doing most of the real work. extension_class<T> is a subclass of PyTypeObject, the struct which Python's 'C' API uses to describe a type. An instance of the extension_class<> becomes the Python type object corresponding to hello::world. When we add it to the module it goes into the module's dictionary to be looked up under the name "world".

Boost.Python uses C++'s template argument deduction mechanism to determine the types of arguments to functions (except constructors, for which we must provide an argument list because they can't be named in C++). Then, it calls the appropriate overloaded functions PyObject* to_python(S) and S'from_python(PyObject*, type<S>) which convert between any C++ type S and a PyObject*, the type which represents a reference to any Python object in its 'C' API. The extension_class<T> template defines a whole raft of these conversions (for T, T*, T&, std::auto_ptr<T>, etc.), using the same inline friend function technique employed by the boost operators library.

Because the to_python and from_python functions for a user-defined class are defined by extension_class<T>, it is important that an instantiation of extension_class<T> is visible to any code which wraps a C++ function with a T, T*, const T&, etc. parameter or return value. In particular, you may want to create all of the classes at the top of your module's init function, then def the member functions later to avoid problems with inter-class dependencies.

Next: Building a Module with Boost.Python Previous: Special Method and Operator Support 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