msgpack / msgpack-c

MessagePack implementation for C and C++ / msgpack.org[C/C++]
Other
3.03k stars 883 forks source link

[QUESTION] msgpack type_error when trying to decode a jpeg after sending it over poco #999

Closed wbehrens-on-gh closed 2 years ago

wbehrens-on-gh commented 2 years ago

repo

I'm trying to encode a cv::Mat to a jpeg then serialize it using msgpack so I can send it over a UDP network using Poco datagram sockets client:

int RoboRIOClient::send() {
        cv::Mat image = cv::imread("/image.jpeg");
        std::stringstream buffer;
        std::vector<uchar> jpg_src;

        if(cv::imencode(".jpg", image, jpg_src)) {
            msgpack::pack(buffer, jpg_src);
            this->_dg_socket.sendBytes(buffer.rdbuf(), sizeof(buffer));
        } else {
            return EXIT_FAILURE;
        } 

        return EXIT_SUCCESS;
    } 

server:

while(true) {
        SocketAddress sender;
        int data = dg_socket.receiveFrom(buf, sizeof(buf) - 1, sender);
        buf[data] = '\0';
        //std::vector<uchar> jpg;
        std::string msg_data(buf); // Do I need to cast this to a string here?
        msgpack::object msg = msgpack::unpack(msg_data.data(), msg_data.size()).get();

        //msg.convert(jpg); 

        cv::Mat image = cv::imdecode(cv::Mat(msg.as<std::vector<uchar>>()), 1);

        cv::imshow(sender.toString(), image);
    }

The problem I'm having is that once the client connects to the server and sends the first packet I imediately get

terminate called after throwing an instance of 'msgpack::v1::type_error'
  what():  std::bad_cast
Aborted (core dumped)

and the server dies, from what I've found that error should only happen if I'm trying to decode the message as the wrong type but I can't get why that would be?

redboltz commented 2 years ago

I'm not sure about your code but I found one problem.

         msgpack::object msg = msgpack::unpack(msg_data.data(), msg_data.size()).get();

should be

         msgpack::object_handle oh = msgpack::unpack(msg_data.data(), msg_data.size());
         msgpack::object msg = oh.get();

because msgpack::object is a reference type.

See https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_object