Jump to: navigation, search

Boost Python Introduction

  • Python is written in C so extension modules can also be written in C/C++ and are basically just shared libraries.


  • Boost Python provides facilities to reduce the amount of boiler-plate code that is required to create a Python extension module.


  • As an introduction let's consider a hello world type example. We have a simple hello function written in C++ in the file mantid.cpp
 // mantid.cpp
 #include <iostream>
 #include <boost/python.hpp>
 
 void sayHello()
 {
   std::cout << "Hello, Python!\n";
 }
 
 BOOST_PYTHON_MODULE(mantid)  // Name here must match the name of the final shared library, i.e. mantid.dll or mantid.so
 {
    boost::python::def("sayHello", &sayHello);
 }


  • The picture below shows how to compile to library and then uses it in Python as it would a normal module.

BoostPythonIntro Demo.png

  • The demo is on a Linux system. In Visual Studio it is enough to create project that outputs a shared library (dll) and ensure the correct include path to Python and library path to boost::python is given. Note that on Windows Boost will automatically add the correct library name so you don't actually need to specify this.

prev next