c++boost.gif (8819 bytes)

A Peek Under the Hood

ExtensionClass<T> is a subclass of PyTypeObject, the struct which Python's 'C' API uses to describe a type. An instance of the ExtensionClass<> 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".

Py_cpp 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 ExtensionClass<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 ExtensionClass<T>, it is important that an instantiation of ExtensionClass<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.

Prev: Overridable Virtual Functions 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.