首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用pybind11共享MPI通信程序

使用pybind11共享MPI通信程序
EN

Stack Overflow用户
提问于 2018-10-05 01:37:25
回答 1查看 355关注 0票数 2

假设我已经为MPI通信器创建了一个包装器:

代码语言:javascript
复制
class Communicator {
   public:
      Communicator() : comm(MPI_COMM_WORLD) {}

      Communicator(int const color, int const key) {
        MPI_Comm_split(MPI_COMM_WORLD, color, key, &comm);
      }

      Communicator(MPI_Comm comm) : comm(comm) {}

      MPI_Comm GetComm() const { return comm; }
    private:
      MPI_Comm comm;
}; 

我想使用pybind11在这个对象周围创建一个python包装器,如下所示:

代码语言:javascript
复制
void CommunicatorWrapper(pybind11::module &m) {
   py::class_<Communicator, std::shared_ptr<Communicator> > commWrap(m, "Communicator");

   commWrap.def(py::init( []() { return new Communicator(); } ));
   commWrap.def(py::init( [](int const color, int const key) { return new Communicator(color, key); } ));
   commWrap.def(py::init( [](MPI_Comm comm) { return new Communicator(comm); } ));
   commWrap.def("GetComm", &Communicator::GetComm);
}

但是,我希望python所看到的MPI_Comm类型是mpi4py.MPI.Comm。这个是可能的吗?如果是这样的话,是怎么做的?

以上(朴素)实现导致以下行为:

代码语言:javascript
复制
comm = Communicator(MPI.COMM_WORLD)

错误:

代码语言:javascript
复制
TypeError: __init__(): incompatible constructor arguments. The following argument types are supported:
1. Communicator()
2. Communicator(arg0: int, arg1: int)
3. Communicator(arg0: int)

代码语言:javascript
复制
comm = Communicator()
print(comm.GetComm())

打印-2080374784。考虑到MPI_Comm是什么,这种行为是有意义的,但显然不是我所需要的功能。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-05 20:22:38

我通过将包装更改为

代码语言:javascript
复制
#include <mpi4py/mpi4py.h>

pybind11::handle CallGetComm(Communicator *comm) {
    const int rc = import_mpi4py();
    return pybind11::handle(PyMPIComm_New(comm->GetComm()));;
}

void CommunicatorWrapper(pybind11::module &m) {
   py::class_<Communicator, std::shared_ptr<Communicator> > commWrap(m, "Communicator");

   commWrap.def(py::init( []() { return new Communicator(); } ));
   commWrap.def(py::init( [](int const color, int const key) { return new Communicator(color, key); } ));
   commWrap.def(py::init( [](pybind11::handle const& comm) {
     const int rc = import_mpi4py();
     assert(rc==0);
     return new Communicator(*PyMPIComm_Get(comm.ptr()));
    } ));
   commWrap.def("GetComm", &CallGetComm);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52657173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档