how to send std::string in MPI?
c++, mpi, string
Solution
You have to send the content of the string buffer obtained from `c_str()`. You don't have to send the string length first as the receiver could simply probe for a message first and then allocate an appropriately-sized buffer:
// Sender
string bla = "blabla";
MPI::COMM_WORLD.Send(bla.c_str(), bla.length(), MPI::CHAR, dest, 1);
// Receiver
MPI::Status status;
MPI::COMM_WORLD.Probe(source, 1, status);
int l = status.Get_count(MPI::CHAR);
char *buf = new char[l];
MPI::COMM_WORLD.Recv(buf, l, MPI::CHAR, source, 1, status);
string bla1(buf, l);
delete [] buf;
Here the receiver uses `Probe` to probe for a matching message and examines the `status` object to find out how many characters are in the message. Then it allocates a buffer of the same size, receives the message and constructs an `std::string` object out of it.
Problem
I want to send a string variable via MPI, but I don't know how should I do it! my code is here: ``` static string fourTupX="Hello"; ``` now I want to send it via MPI: ``` int l=std::strlen(fourTupX.c_str()); l++; MPI::COMM_WORLD.Send (&l,1,MPI::INT,1,7); MPI::COMM_WORLD.Send ( &fourTupX, 1, MPI::CHAR, 1, 1 ); ``` and receive it in another side: ``` int l; source=0; MPI::COMM_WORLD.Recv (&l,1,MPI::INT , source, 7, status1 ); cout<<l; char* myfourTupX=new char[l]; MPI::COMM_WORLD.Recv (myfourTupX,l,MPI_CHAR , source, 1, status1 ); ``` but after receiving there isn't any thing in fourTupx!!! what is the problem?