メッセージ キューのブースト ドキュメントから:
メッセージ キューは、プロセス間で raw バイトをコピーするだけで、オブジェクトを送信しません。これは、メッセージ キューを使用してオブジェクトを送信する場合、オブジェクトはバイナリ シリアル化可能でなければならないことを意味します。たとえば、プロセス間で整数を送信できますが、std::string は送信できません。プロセス間で複雑なデータを送信するには、Boost.Serialization を使用するか、高度な Boost.Interprocess メカニズムを使用する必要があります。
Boost.Serialization を使用してオブジェクトをシリアル化し、受信側で逆シリアル化します。
いくつかの簡単で実用的なコード:
info.hpp
#include <boost/serialization/string.hpp>
#define MAX_SIZE 1000
class info
{
public:
info (int i = 0, std::string n = "")
: id(i), name(n)
{};
int id;
std::string name;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & id;
ar & name;
}
};
send.cpp
#include <string>
#include <sstream>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/archive/text_oarchive.hpp>
#include "info.hpp"
using namespace boost::interprocess;
int main ()
{
try
{
message_queue mq
(
open_or_create,
"mq",
100,
MAX_SIZE
);
info me(1, "asdf");
std::stringstream oss;
boost::archive::text_oarchive oa(oss);
oa << me;
std::string serialized_string(oss.str());
mq.send(serialized_string.data(), serialized_string.size(), 0);
}
catch(interprocess_exception &ex)
{
std::cerr << ex.what() << std::endl;
}
}
受信.cpp
#include <string>
#include <iostream>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "info.hpp"
using namespace boost::interprocess;
int main ()
{
try
{
message_queue mq
(
open_only,
"mq"
);
message_queue::size_type recvd_size;
unsigned int priority;
info me;
std::stringstream iss;
std::string serialized_string;
serialized_string.resize(MAX_SIZE);
mq.receive(&serialized_string[0], MAX_SIZE, recvd_size, priority);
iss << serialized_string;
boost::archive::text_iarchive ia(iss);
ia >> me;
std::cout << me.id << std::endl;
std::cout << me.name << std::endl;
}
catch(interprocess_exception &ex)
{
std::cerr << ex.what() << std::endl;
}
message_queue::remove("mq");
}