简体   繁体   中英

How to send a ZMQ message using a reference?

In the ZMQ_REQ / ZMQ_REP example a buffer is initialized and then the message is copied into it using memcpy .

Specifically:

zmq::message_t reply (5);
memcpy (reply.data (), "World", 5);
socket.send (reply);

How to reply to the message using a char pointer reference?

That is, something along the lines of:

char* text = "Hello";
zmq::message_t reply ();
socket.send (text);

In the example you provided, you are not sending a reference but a pointer.

With the ZMQ API you have to memcpy the data in the message buffer.

You can write your own wrapper function

bool send(zmq::socket_t& socket, const std::string& string) {
    zmq::message_t message(string.size());
    std::memcpy (message.data(), string.data(), string.size());
    bool rc = socket.send (message);
    return (rc);
}

bool send(zmq::socket_t& socket, const char* data) {
    size_t size = strlen(data); // Assuming your char* is NULL-terminated
    zmq::message_t message(size);
    std::memcpy (message.data(), data, size);
    bool rc = socket.send (message);
    return (rc);
}

And then sending your message with something like this :

char* text = "Hello";
send(socket, text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM