SWIG integration with C and C++

Gopesh Bhardwaj
2 min readJul 13, 2021

SWIG(http://www.swig.org/) is a software development tool that simplifies the task of interfacing C and C++ programs to other languages.

While there is a lot of information around this over internet but its scattered across several web pages and that made it difficult for me to find a working example that I could test E2E for my C++ code(backend) and python(frontend). I have attempted to compile everything at one place and have added few of my own findings. As an example, Let’s create a module ‘helloworld’ that can be imported by python CLI and the backend implementation is in C++.

//Test EnvironmentI have chosen docker to test these changes with the following packages:docker run -t -i ubuntu:latest /bin/bash
SWIG Version 4.0.1
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
VIM version 8.1.2269

//HelloWorld.h

//A simple hellowworld classclass HelloWorld
{
public:
HelloWorld();
void sayHello();
};

//HelloWorld.cpp

#include<iostream>
#include “HelloWorld.h”
void HelloWorld::sayHello()
{
std::cout << “hello world” <<std::endl;
}
HelloWorld::HelloWorld()
{
std::cout << “constructor called” <<std::endl;
}
int main()
{
return 0;
}

//HelloWorld.i

//This is an interface file for python to expose methods written in our class%module helloworld
%{
#define SWIG_FILE_WITH_INIT
#include “HelloWorld.h”
%}
%include “HelloWorld.h”

//HelloWorld_wrap.cxx

//create a wrapper that can work as a bridge b/w C++ and pythonswig -python -c++ HelloWorld.i

//setup.py

//create setup.py to build everything at oncefrom distutils.core import setupfrom distutils.extension import Extensionimport osos.environ[“CC”] = “c++”modules = [Extension(‘_helloworld’,sources=[“HelloWorld_wrap.cxx”,”HelloWorld.cpp”],language=”c++”)]setup(name=”helloworld”,ext_modules=modules)

//build the target _helloworld.so that can be imported as python module

python setup.py build_ext -i//This generates the _helloworld.so

Lets test our changes:

root@bae71dcf9567:/workarea# pythonPython 2.7.18 (default, Mar 8 2021, 13:02:45)[GCC 9.3.0] on linux2Type “help”, “copyright”, “credits” or “license” for more information.>>> import helloworld>>> f = helloworld.HelloWorld()constructor called>>> f.sayHello()hello world

Did that work for you? Let me know in a comment.

--

--