DEV Community 👩‍💻👨‍💻

Ziaeemehr
Ziaeemehr

Posted on

MPI for python, wrapping C++ code by swig

There is a nice tutorial for mpi4py, but I think the wrapping C/C++ code with swig is not clear enough. So I introduce my implementation of the tutorial.
The header file contain the hello world example to print the rank of the process.

/* file: helloworld.hpp */
#include "mpi.h"

void sayhello(MPI_Comm comm)
{
    int size, rank;
    MPI_Comm_size(comm, &size);
    MPI_Comm_rank(comm, &rank);
    printf("Hello, World! "
            "I am process %d of %d.\n",
            rank, size);
}

swig interface code:

// file: helloworld.i
%module helloworld

%{
#include "helloworld.hpp"
%}

%include /usr/local/lib/python3.6/dist-packages/mpi4py/include/mpi4py/mpi4py.i
%mpi4py_typemap(Comm, MPI_Comm);

%include "helloworld.hpp"

How to compile:

swig -c++ -python helloworld.i  
mpiCC  -O2 -fPIC -c helloworld_wrap.cxx -I /usr/include/python3.6 -I /usr/local/lib/python3.6/dist-packages/mpi4py/include
mpiCC  -shared helloworld_wrap.o -o _helloworld.so 

The first line produce a helloword_wrap.cxx file.
The second line make the object file helloworld_wrap.o.
and the at the final line shared library file _helloworld.so is made.

How to use:

from mpi4py import MPI
import helloworld

helloworld.sayhello(MPI.COMM_WORLD)
$ mpirun -n 4 python3 runme.py 
Hello, World! I am process 0 of 4.
Hello, World! I am process 1 of 4.
Hello, World! I am process 2 of 4.
Hello, World! I am process 3 of 4.

The get the files please refer to the GitHub directory.
To get more examples wrapping C++ codes using swig, please look at my github repository.

I hope it be helpful.

Top comments (0)

Join us at DEV
Yes, this is technically an “ad”, but really we just want to ask if you want to join DEV. We have 900k+ developers reading, posting, and enjoying community, and would love to have you.   Create an account and continue your coding journey.