Boost.Python is an excellent tool for exposing C++ code to Python. Building Boost with support for the latest version of Python is not that difficult but as most unix systems ship with Python 2.7 or earlier the default options are generally not sufficient.
To start out, make sure that you have the latest version of Python installed. On Ubuntu or debian based environments this is as simple as running the following command.
sudo apt-get install python3-dev
Download and unpack the latest version of Boost then run the following command to bootstrap the Boost build and let it know the appropriate version of python to use.
Now that the environment is ready you can build boost by simply running the b2 command.
./b2 sudo ./b2 install
Due to a bug in the bootstrap.sh file the Python root is not detected. For builds using the Ubuntu package version of Python this is not a problem, however, if you have installed Python to a non-standard location then you may get compile errors. In that case open up the project-config.jam file and add the path to the Python root as in the example below.
python : 3.2 : /usr ;
That’s all there is to it! The following shows an example python module generated via Boost.Python. Save the below text to a file called greet_binding.cpp.
using namespace std;
namespace bp = boost::python;
void say_greeting(const char* name)
cout << "Hello, " << name << "!\n";
Compile the example code with the following options. (Based on Ubuntu’s packaged Python 3.2)
g++ greet_binding.cpp -I/usr/include/python3.2 -I/usr/local/include -lboost_python3 -lpython3.2mu -o greet.so -shared
Now the newly built module is ready to use. To test it out start an instance of the python console and run the following.
>>> import greet >>> greet.say_greeting("Eric") Hello, Eric!