在上一篇中我们介绍了用 Boost.Python 包装 C++ 语言 MPI 程序以供 mpi4py 调用的方法,下面我们将介绍使用 f2py 包装 Fortran MPI 程序的方法。
f2py (Fortran to Python interface generator) 是 numpy 中自带的一个 Fortran 到 Python 的接口生成工具,支持 Fortran 77/90/95,可以使用它将 Fortran 程序包装成可供 Python 调用的扩展模块。感兴趣的读者可以参考其文档,这里不多作介绍。我们只会以简单的例子展示如何使用 f2py 包装 Fortran MPI 程序以供 mpi4py 调用。
假设我们有以下 Fortran 程序文件 helloworld.f90,其中定义了子例程 sayhello,其接受一个 MPI 通信子作为参数。
! helloworld.f90
!
! $ f2py --f90exec=mpif90 -m helloworld -c helloworld.f90
!
subroutine sayhello(comm)
use mpi
implicit none
integer :: comm
integer :: rank, size, nlen, ierr
character (len=MPI_MAX_PROCESSOR_NAME) :: pname
if (comm == MPI_COMM_NULL) then
print *, 'You passed MPI_COMM_NULL !!!'
return
end if
call MPI_Comm_rank(comm, rank, ierr)
call MPI_Comm_size(comm, size, ierr)
call MPI_Get_processor_name(pname, nlen, ierr)
print *, 'Hello, World!', &
' I am process ', rank, &
' of ', size, &