我有一个具有恒定大小(或者我希望如此)的文件,这里定义了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尽可能地缩小数据,根据它们的值打包ints我怀疑这会导致我的FrameData对象的大小略有不同。
有没有办法强制protobuf使用恒定的字段大小?是专门针对int32的吗?
(另一种选择是对所有字段使用bytes类型,但我希望避免这种情况)
发布于 2016-07-20 21:44:19
如果希望整数具有固定长度,则可以使用相应的固定大小整数类型:int32 -> sfixed32、uint32 -> 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.https://stackoverflow.com/questions/38480741
复制相似问题