Python Programming/Extending with C++

There are different ways to extend Python with C and C++ code:
 * In plain C, using Python.h
 * Using Swig
 * Using Boost.Python, optionally with Py++ preprocessing
 * Using pybind11
 * Using ../Cython/.

This page describes Boost.Python. Before the emergence of Cython, it was the most comfortable way of writing C++ extension modules.

Boost.Python comes bundled with the Boost C++ Libraries. To install it on an Ubuntu system, you might need to run the following commands $ sudo apt-get install libboost-python-dev $ sudo apt-get install python-dev

setup.py
Now we can build our module with

python setup.py build

The module `hello.so` will end up in e.g `build/lib.linux-i686-2.4`.

Using the extension module
Change to the subdirectory where the file `hello.so` resides. In an interactive python session you can use the module as follows. >>> import hello >>> hello.say_hello("World") Hello World!

An example with CGAL
Some, but not all, functions of the CGAL library already have Python bindings. Here an example is provided for a case without such a binding and how it might be implemented. The example is taken from the CGAL Documentation.

We then compile and run the module as follows: $ python setup.py build $ cd build/lib* $ python >>> import test >>> test.create_tree Window Query: 3,2.1:c 8,5.1:a Done >>>

Handling Python objects and errors
One can also handle more complex data, e.g. Python objects like lists. The attributes are accessed with the extract function executed on the objects "attr" function output. We can also throw errors by telling the library that an error has occurred and returning. In the following case, we have written a C++ function called "afunction" which we want to call. The function takes an integer N and a vector of length N as input, we have to convert the python list to a vector of strings before calling the function.