我在平台IO中的ESP32项目中使用nanopb。这是一个 arduino 风格的 C++ 代码库。
我正在使用一些 protobufs 对数据进行编码以进行传输。我已经设置了 protobufs 将在根级别使用的内存,以避免每次发送消息时重新分配内存。
// variables to store the buffer/stream the data will render into...
uint8_t buffer[MESSAGE_BUFFER_SIZE];
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// object to hold the data on its way into the encode action...
TestMessage abCounts = TestMessage_init_zero;
然后我有了我的函数,通过protobufs(使用nanoPB)将数据编码到这个流中......
void encodeABCounts(int32_t button_a, int32_t button_b, String message)
{
// populate our data structure...
abCounts.a_count = button_a;
abCounts.b_count = button_b;
strcpy(abCounts.message, message.c_str());
// encode the data!
bool status = pb_encode(&stream, TestMessage_fields, &abCounts);
if (!status)
{
Serial.println("Failed to encode");
return;
}
// and here's some debug code I'll discuss below....
Serial.print("Message Length: ");
Serial.println(stream.bytes_written);
for (int i = 0; i < stream.bytes_written; i++)
{
Serial.printf("%02X", buffer[i]);
}
Serial.println("");
}
好的。所以第一次发生这种编码动作时,这是我在串行监视器中获得的数据......
Message Length: 14
Message: 080110001A087370656369616C41
这很好 - 一切看起来都很好。但是我第二次打电话encodeABCounts()
,第三次,第四次,我得到了这个......
Message Length: 28
Message: 080110001A087370656369616C41080210001A087370656369616C41
Message Length: 42
Message: 080110001A087370656369616C41080210001A087370656369616C41080310001A087370656369616C41
Message Length: 56
Message: 080110001A087370656369616C41080210001A087370656369616C41080310001A087370656369616C41080410001A087370656369616C41
...etc
因此,当新数据进入时,它并没有清除缓冲区/流。每次添加新数据时,缓冲区/流只会变得更长。
如何在不重新分配内存的情况下将流/缓冲区重置为可以对新数据进行编码并停留在其中的状态?
谢谢!