boost Using boost.python Introductory Example on Boost.Python


Things are easy when you have to use a C++ library in a Python project. Just you can use Boost.

First of all here is a list of components you need:

  • A CMakeList.txt file, because you're going to use CMake.
  • The C++ files of the C++ project.
  • The python file - this is your python project.

Let's start with a small C++ file. Our C++ project has only one method which returns some string "This is the first try". Call it CppProject.cpp

char const *firstMethod() {
    return "This is the first try.";

    boost::python::def("getTryString", firstMethod); // boost::python is the namespace

Have a CMakeLists.txt file a below:

cmake_minimum_required(VERSION 2.8.3)


PYTHON_ADD_MODULE(NativeLib CppProject)
FILE(COPY DESTINATION .) # See the whole tutorial to understand this line

By this part of the tutorial everything is so easy. you can import the library and call method in your python project. Call your python project

import NativeLib
print (NativeLib.getTryString)

In order to run your project follow the instructions below:

  • Create a directory with the name build.
  • Enter into that directory.
  • Give the command cmake -DCMAKE_BUILD_TYPE=Release ..
  • make
  • python Now, you have to see the string which the method in your C++ project returns.