有没有办法强制 Protocol Buffer 使用恒定的字段大小?

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

我有一个文件,其中定义了固定大小(或者我希望如此)的 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 尽可能缩小数据,根据它们的值打包整数 - 我怀疑它会导致我的 FrameData 对象的大小略有不同。

有没有办法强制 protobuf 使用恒定的字段大小?专门针对 int32?

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

如果希望整型定长,可以使用对应的定长整型:int32 -> sfixed32, uint32 -> fixed32 ,等等。

但是,我认为 'guess' 序列化 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.