Sending vector of objects in c++ mpi

Let say I have a class named Node which makes the Node with x and y coordinate. Then I make a vector of objects from set of Node. now I want to send this vector of Node with its all properties to another processor.

I tried MPI_Send and it doesn't work in this case. how can I send a vector of objects in MPI?
This is the vector of Node;
1
2
3
4
5
6
7
8
			VecNode_t Nodes;
            for (size_t i_node = 0; i_node < (*Local_Mesh).Nnodes_; i_node++) {
            	VecDbl_t coord = (*Local_Mesh).Coordinates_[i_node];
            	Node node(&coord);
            	Nodes.push_back(node);
				//std::cout << Nodes[i_node].get_x() << " "<< Nodes[i_node].get_y()<<"\t ";
				//std::cout << std::endl;
            }
Last edited on
I would assume whatever you send can't have pointers, since the receiving end might not be on the same process or even the same computer. So you'd need to serialize your data structure. For example, this:
1
2
3
4
5
6
7
8
9
10
std::vector<int *> data_structure;
int *one = new int(42);
int *two = new int(37);
int *three = new int(1024);
data_structure.push_back(one);
data_structure.push_back(one);
data_structure.push_back(two);
data_structure.push_back(one);
data_structure.push_back(three);
send(&data_structure[0], data_structure.size() * sizeof(int *)); //wrong 
would have to be turned into this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::vector<int> ints;
ints.push_back(42);
ints.push_back(37);
ints.push_back(1024);
std::vector<size_t> offsets;
offsets.push_back(0);
offsets.push_back(0);
offsets.push_back(1);
offsets.push_back(0);
offsets.push_back(2);

std::vector<byte> buffer;
auto a = ints.size() * sizeof(int);
auto b = offsets.size() * sizeof(size_t);
buffer.resize(a + b);
memcpy(&buffer[0], &ints[0], a);
memcpy(&buffer[a], &offsetse[0], b);
send(&buffer[0], buffer.size());

You could also use a data exchange format such as JSON:
1
2
3
4
{
    "data_structure": [0, 0, 1, 0, 2],
    "ints": [42, 37, 1024]
}
Last edited on
If (and only if) the object is plain old data then you can try mpi_type_create_struct

https://www.rookiehpc.com/mpi/docs/mpi_type_create_struct.php
What does plain old data mean?
Thanks for your answers
Plain Old Data (POD) means a simple struct or class with no embedded pointers or complex types. i.e. It may not contain for example a std::string, std::vector or other type which manages it's own memory.
Thanks
Topic archived. No new replies allowed.