C++ to Python Bindings

This is a quick walk through of how to take c++ and run it with Python through bindings. If you find yourself wishing to learn more on the topic, Swig’s website for working with Python is a good start. My experience in setting this up was far more tedious than it had to be and I hope this will save people some time. As a note, I currently work on Ubuntu 16.04 and Python 2.7; this will be tailored to those dependencies, however, I do not believe any major changes will be required to the setup.py file based on Swig's website and a Stackoverflow question for Python 3. In addition, the majority of operating systems should be covered by this walk through, with minor tweaks such as yum instead of apt-get for select operating systems.

1. Install


sudo apt-get install python-dev  # python2.x 
sudo apt-get install python3-dev # python3.x


sudo apt-get install swig

This was all I needed to install to get things running, however, if you run into issues let me know so I can update the requirements.

2. Source

c++ Fibonacci implementation, filename: fib.cpp

#include "fib.h"
int fibonacci(int n) {
if(n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);

c++ fibonacci header file, filename: fib.h. I'm going to explain why this file exists in a moment.

int fibonacci(int n);

The next file is the interface file for swig, fib.i. This is telling swig what bindings it will need to create and is why we implemented fib.h.

%module Fibonacci 
#include "fib.h"
%include "fib.h"

The alternative to creating the fib.h file is directly below. For this we define each function individually for swig to then bind.

%module Fibonacci 
int fibonacci(int n);
int fibonacci(int n);

3. Build

setup.py, this file is taken directly from Swig's documentation and modified slightly.

#!/usr/bin/env python
from distutils.core import setup, Extension
fib_module = Extension(
sources=['fib_wrap.cxx', 'fib.cpp'], # fib_wrap.cxx is going to be generated by swig
setup (
name = 'Fibonacci',
version = '0.0',
author = "YOUR_NAME",
description = "Fibonacci swig",
ext_modules = [fib_module],
py_modules = ["Fibonacci"], # name of module that we're going import

build.sh or whatever you fancy.

swig -c++ -python fib.i
python setup.py build_ext --inplace

4. Run

Assign permissions (e.g. chmod 755 build.sh) and run ./build.sh. From there you can go into the python console and test by running the following:

$ python
>>> import Fibonacci
>>> Fibonacci.fibonacci(10)

5. Conclusion

Please let me know if anything here can be improved so I can update this for future readers. Regardless, I hope this helped some of you with your projects/work and saved you some time.

Originally published at gist.github.com.

Like what you read? Give colan biemer a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.