Python Wrappers for C/C++
#day9 of #100daysofcode
Due to exams, I have to put it on hold. But now exams are over and I am back. This time I will finish this challenge continuously because there is no examination coming this time. One good thing happened that our team won the Chandigarh Police Hackathon 2019. It was a great event and I enjoyed it totally. This kind of event motivates me to work harder on myself. That’s why I decided that this time I will complete my challenge without skipping a day. The new year is also coming so have to plan something exciting for the next year.
So let me tell you what I explored today. I was curious how C/C++ code a wrapped to work in Python. So today I explored it and try a sample myself. It was great learning about it. It gives us the power to create a new module for Python from C/C++ code. It is quite easy to create a wrapper for C/C++. If you know how to code in C/C++ then it is very helpful for you.
I used SWIG to create the wrapper. In short, it is a compiler that converts C/C++ code in Python, Rust, etc. languages. It lefts a lot of manual work.
Now I will explain to you step by step the whole process. This is for Linux users. As most of the work is done through the terminal. As I am using Ubuntu so I will explain my workflow. Sorry Windows users. You have to search a little bit and you can find the setup for windows also. I think you have set up a C/C++ compiler and swig and you are good to go.
Let’s jump into the code. The whole code is present on my GitHub here.
I decided to create a sum function under a kj_sum library. I created three file kj_sum.cpp(function definition), kj_sum.i(for swig), kj_sum.h(function declaration).
The file will have all my functions definitions which I want to call in my Python code.
This is for swig. It indicates which are all the header files and functions to include.
Header files are used to declare functions. It is doing the same thing here.
Below are the commands we have to type in our terminal one by one and finally we will have our module ready to import in Python:-
$ sudo apt-get update
$ sudo apt-get install swig
After installing swig type the following in the terminal.
$ swig -python -c++ kj_sum.i$ g++ -c -fpic kj_sum.cpp$ g++ -c -fpic kj_sum_wrap.cxx <path>
At the place of kj_sum, you should place your filename and at the place of <path>, you have to put the path of Python you are using. It would be something like -I/usr/include/python3.6m. To find out your path type the following in the terminal:
$ sudo apt-get install python-dev
$ python-config --cflags
After that do the last step.
$ g++ -shared -fpic example_wrap.o example.o -o _example.so
Now our module is ready to use. Try importing it. If any error occurs let me know in the comment section.