gpt4 book ai didi

java - Java 中 Protocol Buffer 分隔的 I/O 函数是否有 C++ 等效项?

转载 作者:IT老高 更新时间:2023-10-28 13:20:49 25 4
gpt4 key购买 nike

我正在尝试从 C++ 和 Java 文件中读取/写入多个 Protocol Buffer 消息。谷歌建议在消息之前写长度前缀,但默认情况下没有办法这样做(我可以看到)。

但是,2.1.0 版中的 Java API 收到了一组“定界”I/O 函数,它们显然可以完成这项工作:

parseDelimitedFrom
mergeDelimitedFrom
writeDelimitedTo

有 C++ 等价物吗?如果没有,Java API 附加的大小前缀的有线格式是什么,以便我可以在 C++ 中解析这些消息?


更新:

这些现在存在于 google/protobuf/util/delimited_message_util.h从 v3.3.0 开始。

最佳答案

我在这里聚会有点晚了,但是下面的实现包括其他答案中缺少的一些优化,并且在 64MB 输入后不会失败(尽管它仍然对每条单独的消息强制执行 the 64MB limit,只是没有整个流)。

(我是 C++ 和 Java protobuf 库的作者,但我不再为 Google 工作。很抱歉,这段代码从未进入官方库。如果有的话,这就是它的样子。)

bool writeDelimitedTo(
const google::protobuf::MessageLite& message,
google::protobuf::io::ZeroCopyOutputStream* rawOutput) {
// We create a new coded stream for each message. Don't worry, this is fast.
google::protobuf::io::CodedOutputStream output(rawOutput);

// Write the size.
const int size = message.ByteSize();
output.WriteVarint32(size);

uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);
if (buffer != NULL) {
// Optimization: The message fits in one buffer, so use the faster
// direct-to-array serialization path.
message.SerializeWithCachedSizesToArray(buffer);
} else {
// Slightly-slower path when the message is multiple buffers.
message.SerializeWithCachedSizes(&output);
if (output.HadError()) return false;
}

return true;
}

bool readDelimitedFrom(
google::protobuf::io::ZeroCopyInputStream* rawInput,
google::protobuf::MessageLite* message) {
// We create a new coded stream for each message. Don't worry, this is fast,
// and it makes sure the 64MB total size limit is imposed per-message rather
// than on the whole stream. (See the CodedInputStream interface for more
// info on this limit.)
google::protobuf::io::CodedInputStream input(rawInput);

// Read the size.
uint32_t size;
if (!input.ReadVarint32(&size)) return false;

// Tell the stream not to read beyond that size.
google::protobuf::io::CodedInputStream::Limit limit =
input.PushLimit(size);

// Parse the message.
if (!message->MergeFromCodedStream(&input)) return false;
if (!input.ConsumedEntireMessage()) return false;

// Release the limit.
input.PopLimit(limit);

return true;
}

关于java - Java 中 Protocol Buffer 分隔的 I/O 函数是否有 C++ 等效项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2340730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com