Debian Codegraph @

python/src/mpi_casters.h

raw
1 // Copyright (C) 2017 Chris Richardson, Garth N. Wells and Tormod Landet
2 //
3 // This file is part of DOLFIN.
4 //
5 // DOLFIN is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU Lesser General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // DOLFIN is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public License
16 // along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
17
18 #ifndef _DOLFIN_PYBIND11_MPI
19 #define _DOLFIN_PYBIND11_MPI
20
21 #include <pybind11/pybind11.h>
22 #include "MPICommWrapper.h"
23 #include <dolfin/common/SubSystemsManager.h>
24
25 // Macro for casting between dolfin and mpi4py MPI communicators
26 #ifdef HAS_MPI
27 #ifdef HAS_PYBIND11_MPI4PY
28 #include <mpi4py/mpi4py.h>
29
30 // Import mpi4py on demand
31 #define VERIFY_MPI4PY(func) \
32 if (!func) \
33 { \
34 dolfin::SubSystemsManager::init_mpi(); \
35 int rc = import_mpi4py(); \
36 if (rc != 0) \
37 { \
38 std::cout << "ERROR: could not import mpi4py!" << std::endl; \
39 throw std::runtime_error("Error when importing mpi4py"); \
40 } \
41 }
42
43 namespace pybind11
44 {
45 namespace detail
46 {
47 template <> class type_caster<dolfin_wrappers::MPICommWrapper>
48 {
49 public:
50 // Define this->value of type MPICommWrapper
51 PYBIND11_TYPE_CASTER(dolfin_wrappers::MPICommWrapper, _("MPICommWrapper"));
52
53 // Python to C++
54 bool load(handle src, bool)
55 {
56 // Simplified version of isinstance(src, mpi4py.MPI.Comm) - avoids segfault
57 // when pybind11 tries to convert some other random type to MPICommWrapper
58 if (not hasattr(src, "Allgather"))
59 return false;
60 VERIFY_MPI4PY(PyMPIComm_Get);
61 value = dolfin_wrappers::MPICommWrapper(*PyMPIComm_Get(src.ptr()));
62 return true;
63 }
64
65 // C++ to Python
66 static handle cast(dolfin_wrappers::MPICommWrapper src,
67 pybind11::return_value_policy policy, handle parent)
68 {
69 VERIFY_MPI4PY(PyMPIComm_New);
70 return pybind11::handle(PyMPIComm_New(src.get()));
71 }
72
73 operator dolfin_wrappers::MPICommWrapper()
74 {
75 return this->value;
76 }
77 };
78 }
79 }
80
81 #endif // HAS_PYBIND11_MPI4PY
82 #endif // HAS_MPI
83 #endif