Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of boost. Click here for the latest Boost documentation.
Embedding

By now you should know how to use Boost.Python to call your C++ code from Python. However, sometimes you may need to do the reverse: call Python code from the C++-side. This requires you to embed the Python interpreter into your C++ program.

Currently, Boost.Python does not directly support everything you'll need when embedding. Therefore you'll need to use the Python/C API to fill in the gaps. However, Boost.Python already makes embedding a lot easier and, in a future version, it may become unnecessary to touch the Python/C API at all. So stay tuned...

Building embedded programs

To be able to use embedding in your programs, they have to be linked to both Boost.Python's and Python's static link library.

Boost.Python's static link library comes in two variants. Both are located in Boost's /libs/python/build/bin-stage subdirectory. On Windows, the variants are called boost_python.lib (for release builds) and boost_python_debug.lib (for debugging). If you can't find the libraries, you probably haven't built Boost.Python yet. See Building and Testing on how to do this.

Python's static link library can be found in the /libs subdirectory of your Python directory. On Windows it is called pythonXY.lib where X.Y is your major Python version number.

Additionally, Python's /include subdirectory has to be added to your include path.

In a Jamfile, all the above boils down to:

    projectroot c:\projects\embedded_program ; # location of the program

    # bring in the rules for python
    SEARCH on python.jam = $(BOOST_BUILD_PATH) ;
    include python.jam ;

    exe embedded_program # name of the executable
      : #sources
         embedded_program.cpp
      : # requirements
         <find-library>boost_python <library-path>c:\boost\libs\python
      $(PYTHON_PROPERTIES)
        <library-path>$(PYTHON_LIB_PATH)
        <find-library>$(PYTHON_EMBEDDED_LIBRARY) ;

Getting started

Being able to build is nice, but there is nothing to build yet. Embedding the Python interpreter into one of your C++ programs requires these 4 steps:

  1. #include <boost/python.hpp>

  2. Call Py_Initialize() to start the interpreter and create the __main__ module.

  3. Call other Python C API routines to use the interpreter.

  4. Call Py_Finalize() to stop the interpreter and release its resources.

(Of course, there can be other C++ code between all of these steps.)

Now that we can embed the interpreter in our programs, lets see how to put it to use...