【发布时间】:2012-09-09 16:58:48
【问题描述】:
我的动机是将 MPI 信息从 python 有效地传递给通过 ctypes 调用的 C 函数。我在 python 中使用 mpi4py 进行 MPI 绑定。我想通过一个用 C 编写并通过 python 中的 ctypes 调用的简单示例 MPI 代码来学习它。我已经详细说明了我在下面运行时遇到的步骤和错误。
C 代码 [passMpi4Py.c]
#include <stdio.h>
#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);
}
我用gcc/openmpi-1.6编译了上面的c代码如下:
mpicc -shared -Wl,-soname,passMpi4Py -o passMpi4Py.so -fPIC passMpi4Py.c
Python 包装器 [passMpi4PyWrapper.py]
import ctypes
from mpi4py import MPI
testlib = ctypes.CDLL('path-to-file/passMpi4Py/passMpi4Py.so')
testlib.sayhello(MPI.COMM_WORLD)
当我尝试使用运行上述代码时
mpirun -np 4 python passMpi4PyWrapper.py
我收到以下错误
Traceback (most recent call last):
Traceback (most recent call last):
File "passMpi4PyWrapper.py", line 5, in <module>
Traceback (most recent call last):
File "passMpi4PyWrapper.py", line 5, in <module>
File "passMpi4PyWrapper.py", line 5, in <module>
Traceback (most recent call last):
testlib.sayhello(MPI.COMM_WORLD)
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
testlib.sayhello(MPI.COMM_WORLD)
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
testlib.sayhello(MPI.COMM_WORLD)
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
File "passMpi4PyWrapper.py", line 5, in <module>
testlib.sayhello(MPI.COMM_WORLD)
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
更新:
在 C 程序 MPI 函数中使用 *MPI_COMM_WORLD* 而不是 comm 可以帮助我消除错误。但是我仍然想知道这是否是将 MPI 信息传递给 C 程序的最佳方式。
【问题讨论】:
-
你试过没有通讯器吗?例如在
sayhello中硬编码MPI_COMM_WORLD? -
我刚试过,但是我必须在 sayhello 中为 MPI_COMM_WORLD 提供什么数据类型,否则编译 C 代码时会出错
-
不,我的意思是让
sayhello成为一个接受 0 个参数的函数。例如void sayhello(){ ...; MPI_Comm_size(MPI_COMM_WORLD,&size);... } -
这里的一个问题是
MPI_COMM_WORLD的类型是MPI_Comm类型,它几乎可以是任何类型。它可以是typedefed 到int,long,long long... 或者它甚至可以是某种struct(标准没有说)`。很可能,在大多数系统上它是一个 4 字节整数以与 fortran 绑定兼容,但这绝对不能保证。 -
酷。您建议的 MPI_COMM_WORLD 现在有效。谢谢你。但这是将 MPI 信息从 python 包装器发送到 C 代码的最佳方式吗?您是否知道任何详细处理此问题的书籍或在线教程?