简体   繁体   English

如何发送不同长度的消息而没有结尾字节\\ x00?

[英]How to send a message of different lengths without trailing bytes \x00?

What does 20 inside message() mean vs the 20 after message.data(), in the below code? 什么20的内部message()的意思是VS的20message.data(),在下面的代码?

zmq::message_t message(20);
snprintf ((char *) message.data(), 20 ,"%05d %d %d", zipcode, temperature, relhumidity);
publisher.send(message);

From reading the documentation, message(20) initialises the message to be 20 bytes long. 通过阅读文档, message(20)将消息初始化为20个字节长。 What does the 20 after message.data(), do? message.data(),之后的20做什么的?

How to change the size of the message to send the message without trailing bytes \\x00 ? 如何更改消息的大小以发送消息而不尾随字节\\x00 Can "%05d %d %d", zipcode, temperature, relhumidity be declared outside and the length of that variable be used to initiate the message and send it? 是否可以在外部声明"%05d %d %d", zipcode, temperature, relhumidity并且可以使用该变量的长度来发起消息并发送?

You can use snprintf() with a limit of zero to measure how large the data will be before allocating the space for it: 您可以使用限制为零的snprintf()来测量数据的大小,然后再为其分配空间:

auto length = std::snprintf(nullptr, 0, "%05d %d %d", zipcode, temperature, relhumidity) + 1;
// +1 to account for null terminating character.

zmq::message_t message(length);

std::snprintf(
    static_cast<char *>(message.data()), length,
    "%05d %d %d", zipcode, temperature, relhumidity
);

publisher.send(message);

You could also format into a local buffer that you know is large enough, measure the string's length, then copy it: 您还可以格式化为一个已知足够大的本地缓冲区,测量字符串的长度,然后将其复制:

char buffer[64];

auto length = std::snprintf(buffer, 64, "%05d %d %d", zipcode, temperature, relhumidity) + 1;

zmq::message_t message(length);

std::copy(buffer, buffer + length, static_cast<char *>(message.data());

publisher.send(message);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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