开发者

How to pass complex objects ( std::string ) through boost::interprocess::message queue

Does anybody have some example code showing the pipeline of serializing a std::string sending it through开发者_开发百科 a boost::interprocess::message_queue and getting it back out again?


You need to serialize your data because boost::interprocess::message_queue operates on byte arrays. If all your messages are strings, just do:

size_t const max_msg_size = 0x100;
boost::interprocess::message_queue q(..., max_msg_size);

// sending
std::string s(...);
q.send(s.data(), s.size(), 0);

// receiving
std::string s;
s.resize(max_msg_size);
size_t msg_size;
unsigned msg_prio;
q.receive(&s[0], s.size(), msg_size, msg_prio);
s.resize(msg_size);


A solution can be to write a function that has as input the object you want to send (e.g. your variable size string), and as output a container of objects of fixed size.

Something like:

int Tokenize(std::vector<MessageToken>&, const Message&) const;
int Merge(Message&, const std::vector<MessageToken>&) const;                                    

Then these fixed size objects can be sent in/extracted from the message_queue.

The advantage compared to Maxim's solution is that you do not need to specify a max_msg_size parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜