Boost: De-serializing a custom C++ object passed over ZeroMQ pull socket

穿精又带淫゛_ 提交于 2019-12-02 05:58:47

You declared theMsg as a pointer (GenericMessage<std::string> *theMsg;).

Try changing that line to GenericMessage<std::string> theMsg;.`

The real source of your exception

In the GenericMessage default constructor, you initialize data with NULL. However, you aren't allowed to initialize a std::string with a NULL pointer. Don't initialize your data member in the default constructor.

GenericMessage()
: beId(-1) 
{}

As long as your type T has a default constructor, the compiler will handle its initialization when the template is generated.

(hopefully) helpful hint #1

The data buffer in a zmq::message_t is (generally) not NULL-terminated. After you receive the message, be careful about how you convert the buffer to a string.

// snip
zmq::message_t reply;
socket.recv (&reply);

const char *buf = static_cast<const char*>(reply.data());
std::cout << "CHAR [" << buf << "]" << std::endl;

//std::string input_data_(buf);  // assumes a null-term string
std::string input_data_( buf, reply.size() ); 
// snip

(hopefully) helpful hint #2

Also, I noticed something in ZmqHandler.hxx.

// snip
std::string outbound_data_ = archive_stream.str();
const char * buf = outbound_data_.c_str();    
int len = strlen((const char*)buf);
std::cout << "LENGTH [" << len << "]" << std::endl;

zmq::message_t msgToSend(len);

memcpy ((char *) msgToSend.data(), buf, len);

if(memcmp((char *) msgToSend.data(), buf, len) != 0)
{
  std::cout << "memcpy error!" << std::endl;
}
// snip

You don't need to check the results of the memcpy (unless you want to check its return value). The whole block could be changed to something like this:

std::string outbound_data_ = archive_stream.str();
// no need to use the c-style string function 'strlen'
int len = outbound_data_.length();
std::cout << "LENGTH [" << len << "]" << std::endl;

zmq::message_t msgToSend(len);
memcpy( msgToSend.data(), outbound_data_.data(), len );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!