我正在尝试包装一个 C 函数MPI_Comm
通过 cython 通信器句柄作为参数。因此,我希望能够从 python 调用该函数,并将其传递给mpi4py.MPI.Comm
目的。我想知道的是,如何进行转换mpi4py.MPI.Comm
to MPI_Comm
.
为了进行演示,我使用一个简单的“Hello World!”类型函数:
helloworld.h
:
#ifndef HELLOWORLD
#define HELLOWORLD
#include <mpi.h>
void sayhello(MPI_Comm comm);
#endif
helloworld.c
:
#include <stdio.h>
#include "helloworld.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);
}
我现在想从 python 中调用这个函数,如下所示:
from_python.py
:
import mpi4py
import helloworld_wrap
helloworld_wrap.py_sayhello(mpi4py.MPI.COMM_WORLD)
意思是mpirun -np 4 python2 from_python.py
应该给出类似的东西:
你好世界!我是 4 个进程中的第 0 个进程。
你好世界!我是 4 个进程中的第 1 个。
你好世界!我是 4 个进程中的第 2 个。
你好世界!我是 4 个进程中的第 3 个。
但如果我尝试通过 cython 来实现这一点,如下所示:
helloworld_wrap.pyx
:
cimport mpi4py.MPI as MPI
cimport mpi4py.libmpi as libmpi
cdef extern from "helloworld.h":
void sayhello(libmpi.MPI_Comm comm)
def py_sayhello(MPI.Comm comm):
sayhello(comm)
and:
setup.py
:
import os
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
mpi_compile_args = os.popen("mpicc --showme:compile").read().strip().split(' ')
mpi_link_args = os.popen("mpicc --showme:link").read().strip().split(' ')
ext_modules=[
Extension("helloworld_wrap",
sources = ["helloworld_wrap.pyx", "helloworld.c"],
language = 'c',
extra_compile_args = mpi_compile_args,
extra_link_args = mpi_link_args,
)
]
setup(
name = "helloworld_wrap",
cmdclass = {"build_ext": build_ext},
ext_modules = ext_modules
)
我收到以下错误消息:
helloworld_wrap.pyx:8:13:无法将 Python 对象转换为“MPI_Comm”
表明mpi4py.MPI.Comm
无法转换成MPI_Comm
。那么我该如何转换mpi4py.MPI.Comm
进入一个MPI_Comm
为了让我的包装工作?