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

前端 未结 1 1188
悲哀的现实
悲哀的现实 2021-01-24 01:48

The text I am writing here is a follow up problem that I opened up earlier in another thread at Boost: Serializing/De-serializing a custom C++ object passed over ZeroMQ pull soc

1条回答
  •  逝去的感伤
    2021-01-24 02:25

    You declared theMsg as a pointer (GenericMessage *theMsg;).

    Try changing that line to GenericMessage 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(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 );
    

    0 讨论(0)
提交回复
热议问题