Wei Zhang's Blog

06 Oct 2021

Interface C++/Python codes using swig

swig is a software development tool that connects codes written in different languages. In this post, I give an example and show how it can be used to connect C++ and Python codes. See the document here for details.

Suppost that we want to define two classes in C++. The first class is called Myclass, which has a member function that prints some simple information. The second class is called MyAbs, which can compute the absolute value of an input real number.

Goal: provide Python wrapers for these two classes, so that we can use them in Python codes.

Steps:

  1. First, we define the two classes in the header file.

myclass.h

#include<cmath>
#include<iostream>

class Myclass {
  public:
    void print_info () ;
};

class MyAbs{
  public:
    void calc_abs(double x) ;
};
  1. Second, we implement their member functions in the cpp file below.

myclass.cpp

#include "myclass.h"

void Myclass::print_info ()
    {
      std::cout << "This is a C++ class\n" ;
    }

void MyAbs::calc_abs(double x)
    {
      std::cout << "The absolute value of " << x << " is: " << fabs(x) << std::endl ;
    }
  1. Third, we write the interface file that is required by swig.

myclass.i

%module myclass
%{
#include "myclass.h"
%}

class Myclass {
  public:
    void print_info () ;
};

class MyAbs{
  public:
    void calc_abs(double x) ;
};
  1. Forth, we create a script for building the extension module for python.

setup.py

from distutils.core import setup, Extension
import os

os.environ["CC"] = "g++"

myclass_module = Extension('_myclass',
                           sources=['myclass_wrap.cxx', 'myclass.cpp'],
                           extra_compile_args = ['-std=c++11'],
                           swig_opts=['-c++', '-py3'],
                           )

setup (name = 'myclass',
       version = '0.1',
       author      = "Wei Zhang",
       description = """Simple swig example""",
       ext_modules = [myclass_module],
       py_modules = ["myclass"],
       )
  1. Lastly, we build the extension by running the following two commands in bash.
swig -c++ -python -py3 myclass.i
python setup.py build_ext --inplace

Result: After the above steps, we can call the two c++ classes in Python:

>>> import myclass
>>> myclass.Myclass().print_info() 
This is a C++ class
>>> myclass.MyAbs().calc_abs(-3)
The absolute value of -3 is: 3

Tags