3 minutes
Writing Python modules in C++
How to build libraries in C++ and use them in Python
In this post I will expose one way to create libraries in C++ and expose them to Python.
This can be very useful when we want to integrate existing piece of code, or write new code that perform better than Python.
The way exposed in this post will make use of Boost, a peer reviewed C++ set of libraries. In paticular, we will use Boost-Python
Installing Boost
The first step is to install the package Boost
:
wget https://dl.bintray.com/boostorg/release/1.75.0/source/boost_1_75_0.tar.gz
tar -xzf boost_1_75_0.tar.gz
We can try if everything is working correctly, with a simple program with Boost (copied from the original documentation)
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
using namespace boost::lambda;
typedef std::istream_iterator<int> in;
std::for_each(
in(std::cin), in(), std::cout << (_1 * 3) << " " );
}
And we compile
c++ -I ./boost_1_75_0 test-boost.cc -o test-boost
We can see that it works if we get the following output running the program
luis@BARE:~/projects/How to build libraries in CPP to use in Python$ echo 1 2 3 | ./test-boost
3 6 9
luis@BARE:~/projects/How to build libraries in CPP to use in Python$
Installing Boost-Python
First let’s enter into the boost directory boost_1_75_0
and we can run ./bootstrap.sh --show-libraries
to see the non-header only libraries provided by Boost.
We should see something similar to this at the end
The Boost libraries requiring separate building and installation are:
- atomic
- chrono
- container
- context
- contract
- coroutine
- date_time
- exception
- fiber
- filesystem
- graph
- graph_parallel
- headers
- iostreams
- json
- locale
- log
- math
- mpi
- nowide
- program_options
- python
- random
- regex
- serialization
- stacktrace
- system
- test
- thread
- timer
- type_erasure
- wave
Now we can install Boost-Python prepare the environment to use Python:
./bootstrap.sh --with-libraries=python
And with the b2
tool generated while running bootstrap.sh
, we can compile and install Boost-Python
sudo ./b2 install
If you ignore the step of specifying the libraries to build, the full build with take a long time….
Example
First, let’s copy the content of the tutorial included with Boost into the folder example-1
cp -Rf boost_1_75_0/libs/python/example/tutorial/* example-1/
We should have three files in the folder
luis@BARE:~/projects/How to build libraries in CPP to use in Python/example-1$ ls
hello.cpp hello.py Jamfile
luis@BARE:~/projects/How to build libraries in CPP to use in Python/example-1$
Now we execute bjam and next we execute python hello.py
. If everything went well, we should see hello world!
as the output.
In the future I will write a post and how to implement a library to operate with complex numbers in C++ and its use in Python