问题描述
我使用zeromq与protobuf发送/接收消息,但代码在接收端崩溃与分段故障(内核转储)
错误时解析接收的数据。 p>
扫描
是我的邮件。
.cpp
扫描proto_ls_msg;
proto_ls_msg.set_angle_min(0.0);
proto_ls_msg.set_angle_max(180.5);
std :: string ls_msg_str;
proto_ls_msg.SerializeToString(& ls_msg_str);
zmq :: message_t request(ls_msg_str.size());
memcpy(request.data(),ls_msg_str.c_str(),ls_msg_str.size());
socket.send(request);
collector.cpp
zmq :: message_t recieved;
socket.recv(& recieved);
//感谢πάνταῥεῖ
std :: string ls_msg_str((char *)recieved.data(),recieved.size());
Scan * pb_laser_msg_rcv;
pb_laser_msg_rcv-> ParseFromString(ls_msg_str); //< - Segmentation fault here
我尝试了不同的转换方式 zmq :: message_t
到 std :: string
,但仍然会产生分段错误。
编辑更新:
// std :: string ls_msg_str((char *)recieved);
std :: string ls_msg_str((char *)recieved.data(),recieved.size()); 解决方案 / div> IIRC,您不能直接将 zmq :: message_t
转换为字符串。您应该只能使用 data
成员来创建字符串。
同样 recieved.data
不是'\0'
终止,因此您还需要构造 ls_msg_str
实例时传递大小:
std :: string ls_msg_str((char *)recieved.data,recieved.size);
// ^^^^ ^^^^
I am using zeromq with protobuf to send/recieve messages but code was crashing on receiver end with Segmentation fault (core dumped)
error while parsing the received data.
Scan
is my message.
sender.cpp
Scan proto_ls_msg;
proto_ls_msg.set_angle_min(0.0);
proto_ls_msg.set_angle_max(180.5);
std::string ls_msg_str;
proto_ls_msg.SerializeToString(&ls_msg_str);
zmq::message_t request (ls_msg_str.size());
memcpy (request.data(), ls_msg_str.c_str(),ls_msg_str.size());
socket.send (request);
collector.cpp
zmq::message_t recieved;
socket.recv (&recieved);
//thanks to πάντα ῥεῖ
std::string ls_msg_str((char*)recieved.data(),recieved.size());
Scan *pb_laser_msg_rcv;
pb_laser_msg_rcv->ParseFromString(ls_msg_str); // <-- Segmentation fault here
I tried different way of converting zmq::message_t
to std::string
but still it gives segmentation fault.
Edit update:
//std::string ls_msg_str((char*)recieved);
std::string ls_msg_str((char*)recieved.data(),recieved.size());
thanks.
解决方案 IIRC you can't directly cast a zmq::message_t
to a string. You should probably only use the data
member to create the string.Also the recieved.data
is not '\0'
terminated, so you would also need to pass the size when you construct the ls_msg_str
instance:
std::string ls_msg_str((char*)recieved.data,recieved.size);
// ^^^^ ^^^^
这篇关于zeromq与protobuf分段错误,而解析在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-05 07:55