4.12.4.0.1 C and C++

The C++ language interface provides the functions listed below for mixed-language interoperability. The token <CLASS> is used below to indicate any valid MPI-/ opaque handle name (e.g., Group), except where noted. For the case where the C++ class corresponding to <CLASS> has derived classes, functions are also provided for converting between the derived classes and the C MPI_<CLASS>.

The following function allows assignment from a C MPI-/ handle to a C++ MPI-/ handle.


MPI::<CLASS>& MPI::<CLASS>::operator=(const MPI_<CLASS>& data)



The constructor below creates a C++ MPI-/ object from a C MPI-/ handle. This allows the automatic promotion of a C MPI-/ handle to a C++ MPI-/ handle.


MPI::<CLASS>::<CLASS>(const MPI_<CLASS>& data)



Example 4..10   In order for a C program to use a C++ library, the C++ library must export a C interface that provides appropriate conversions before invoking the underlying C++ library call. This example shows a C interface function that invokes a C++ library call with a C communicator; the communicator is automatically promoted to a C++ handle when the underlying C++ function is invoked.

// C++ library function prototype
void cpp_lib_call(MPI::Comm& cpp_comm);

// Exported C function prototype
extern "C" {
void c_interface(MPI_Comm c_comm);
}

void c_interface(MPI_Comm c_comm)
{
// the MPI_Comm (c_comm) is automatically promoted to MPI::Comm
cpp_lib_call(c_comm);
}

The following function allows conversion from C++ objects to C MPI-/ handles. In this case, the casting operator is overloaded to provide the functionality.


MPI::<CLASS>::operator MPI_<CLASS>() const



Example 4..11   A C library routine is called from a C++ program. The C library routine is prototyped to take an MPI_Comm as an argument.

// C function prototype
extern "C" {
void c_lib_call(MPI_Comm c_comm);
}

void cpp_function()
{
// Create a C++ communicator, and initialize it with a dup of
//   MPI::COMM_WORLD
MPI::Intracomm cpp_comm(MPI::COMM_WORLD.Dup());
c_lib_call(cpp_comm);
}

Rationale. Providing conversion from C to C++ via constructors and from C++ to C via casting allows the compiler to make automatic conversions. Calling C from C++ becomes trivial, as does the provision of a C or Fortran interface to a C++ library.(End of rationale.)

Advice to users. Note that the casting and promotion operators return new handles by value. Using these new handles as INOUT parameters will affect the internal MPI object, but will not affect the original handle from which it was cast.(End of advice to users.)

It is important to note that all C++ objects and their corresponding C handles can be used interchangeably by an application. For example, an application can cache an attribute on MPI_COMM_WORLD and later retrieve it from MPI::COMM_WORLD.

MPI-Standard for MARMOT