有没有办法强制Protocol Buffer使用常量字段大小

Is there a way to force Protocol Buffer to use the constant field size?

本文关键字:常量 字段 Buffer Protocol 有没有      更新时间:2023-10-16

我有一个文件,其中定义了大小不变(或者我希望如此)的protobuf消息:

message FrameData {
    required int32 index = 1;
    required bytes timeStamp = 2;
    required int32 timeStampSize = 3;
    required bytes frame = 4;
    required int32 frameSize = 5;
}

该文件包含数百条protobuf消息,并且所有帧的大小应该始终相同。然而,当我加载文件时,我注意到我有时会得到损坏的数据,通常是在index具有宽动态范围时。

Protobuf尽可能地缩小数据,根据int的值打包int——我怀疑这会导致我的FrameData对象的大小略有不同。

有没有办法强迫质子束使用恒定的场大小?具体针对int32?

(另一种选择是对所有字段使用bytes类型,但我希望避免这种情况)

如果您希望整数具有固定长度,可以使用相应的固定大小整数类型:int32->sfixed32uint32->fixed32等等

然而,我认为"猜测"序列化的protobuf消息的长度不是一个好主意。相反,您还应该将长度保存在文件中。例如:

FILE *fp = fopen("data", "w");
FrameData frame;
string serialized;
frame.SerializeToString(&serialized);
// write length first
size_t length = serialized.size();
fwrite(reinterpret_cast<const char*>(&length), sizeof(length), 1, fp);
// then write the serialized data
fwrite(serialized.c_str(), 1, serialized.size(), fp);
// write other protobuf messages

解析文件时:

FILE *fp = fopen("data", "r");
size_t length = 0;
// read length first
fread(&length, sizeof(length), 1, fp);
// then read serialized data
char *buf = new char[length];
fread(buf, length, 1, fp);
// Parse protobuf
FrameData frame;
frame.ParseFromArray(buf, length);
// read other messages.