Hello Boost Python

14 April 2018

Boost.Python makes it simple to expose any C++ functions or classes to the python interpreter. This page is a tiny but complete example of just how easy it is. The Boost.Python documentation has a hello world example that I’ve lightly edited to include:

Here’s a two-line python script that calls the module we’re about to build:

#!/usr/bin/env python
import hello
print(hello.greet('World!'))

The C++ function is defined and exposed by these few lines:

#include <boost/python.hpp>
#include <string>

std::string greet(std::string name)
{
  return std::string("Hello, ") + name;
}

BOOST_PYTHON_MODULE(hello)
{
  using namespace boost::python;
  def("greet", greet, "Prepends a greeting to the passed name");
}

At this stage, the official documentation uses Boost Build’s bjam, which works but you shouldn’t build your own projects with it. No-one else does either.

CMake

This CMakeLists.txt file works natively on Ubuntu 17.10 with the boost (1.62) installed by sudo apt-get install libboost-all-dev. It’ll also work with one you build and install yourself, and with whatever you like on Windows. Boost.Python is not a header-only library.

cmake_minimum_required(VERSION 3.0)
find_package(PythonLibs 3 REQUIRED)
#To prevent attempts to link to python2 libraries, specify
#the version of libboost_python
#See https://gitlab.kitware.com/cmake/cmake/issues/16391
if(UNIX)
  set(BOOST_PYTHONLIB python-py36)
else()
  set(BOOST_PYTHONLIB python3)
endif()
find_package(Boost COMPONENTS ${BOOST_PYTHONLIB})

python_add_module(hello hello.cpp)

target_include_directories(hello PUBLIC
  ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})
target_link_libraries(hello
  ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})

Normal cmake ../src && make will weave the C++ into the python module hello.so (hello.pyd on Windows). Don’t install it globally - either put it to the same directory as the calling python script (for temporary use) or copy it into the site-packages directory of venv.

python
boost-python
cmake