对 Protocol Buffers 中 Message::ParseFromIstream 的使用感到困惑

Confused regarding the use of Message::ParseFromIstream in Protocol Buffers

我收到的数据为 unsigned char*,其中包含一个字节数组。

unsigned char* byteptr = static_cast<unsigned char*>(msg.data());

我想初始化我的协议缓冲区,它是一个地址簿。我认为最好的匹配是使用 ParseFromIstream 如下:

my_address_book.ParseFromIstream()

关于字节数组,也就是unsigned char*。由于编译时不知道字节数组的长度,所以有两种选择:

方案一.变长数组

unsigned char bytearray[msg.size()];
std::copy(byteptr, byteptr + msg.size(), bytearray);

选项 2. 动态分配数组并在完成后将其删除

unsigned char* bytearray = new unsigned char [msg.size()];
std::copy(byteptr, byteptr + msg.size(), bytearray);

我有以下问题:

  1. unsigned char*的情况下如何使用ParseFromIstream
  2. 考虑到更好的性能(执行速度快)是优先考虑的,以上两个选项中哪个选项最好?

你应该使用 ParseFromArray(),它需要一个指针和一个大小:

my_address_book.ParseFromArray(msg.data(), msg.size())

根本不需要将数据复制到新数组中。