2011 Oct 02

This is my example of wrapping C++ objects with python. It is different from the many excellent examples already available on the web in that I am implementing a Cartesian space vector as a python number wrapping a C++ implementation with all of its operators overloaded so it also behaves as "a number". This example follows the python documentation for extending python with C or C++ and the Python/C API Referencd Manual (version 2.7.2 at the time this was written). I also include Python Number Object Structures as a useful reference for this example. The reader should also know there are useful tools that will do this for you like boost.python and SWIG.

The difference here between the python wrapping C++ examples I found is how to implement as_number with methods that return a new SpaceType that are part of the SpaceType data structure. That is to say how do you define a method that returns a SpaceType that is part of the SpaceType structure itself? The solution I found was to forward declare a function, new_SpaceType(Space** a_space). This wraps PyObject_New(Space, &SpaceType) so as_number operators can refer to it while defining SpaceType and let the linker resolve the final implementation.

The icing on this cake is to be able to use python's unit test to make sure it all works.

As always, please let me know what you think.

-lrm