Search code examples
c++structmpimpich

C++ MPI create and send array of structs which has fields char[16] and integer


I know there is a question on the site here about this but that is implemented in c. I need c++ version of it.

Problem is the following: I created a struct which has the following form

struct word
{
   char value[WORD_MAX_LENGTH];
   int freq;
};

I need to send the array of these structs. How can I serialize this struct and send say 500 of them to another process using MPI_Send.

Here is where I got so far:

    MPI_Datatype word_type, oldtypes[2];
    int blockcounts[2];
    MPI_Aint offsets[2], extent;

    //Determine the offset and block length of the first element of the struct which is a char array.
    offsets[0] = 0;
    oldtypes[0] = MPI_CHAR;
    blockcounts[0] = WORD_MAX_LENGTH;

    //Determine the offset of int ferq of the struct.
    MPI_Type_extent(MPI_CHAR, &extent);
    offsets[1] = 16 * extent;
    blockcounts[1] = 1;

    // Finally create the type.
    MPI_Type_create_struct(2, blockcounts, offsets, oldtypes, &word_type);
    MPI_Type_commit(&word_type);

When I do this, it compiles with no error however when I try to run it. It complains

Fatal error in PMPI_Type_create_struct: Invalid datatype, error stack:

PMPI_Type_create_struct(173): MPI_Type_create_struct(count=2, 
array_of_blocklengths=0x7fffbd059f70,   
array_of_displacements=0x7fffbd059f80, array_of_types=0x7fffbd059f60, 
newtype=0x7fffbd059f14) failed

PMPI_Type_create_struct(142): Invalid datatype

Any help will be appreciated. Note: I can't use boost libraries.


Solution

  • There are at least two issues

    • oldtypes[1] is not initialized
    • offsets[1] looks odd, you can use the offsetsof() macro instead

    You might also have to MPI_Type_create_resized() if your compiler adds some padding at the end of the word strict.