問題:
開發人員嘗試讀取和寫入多個Protocol Buffers 訊息從C 和Java 中的檔案使用Java 中可用的「定界」I/O函數可能會遇到問題,但看起來並非如此可在 C 中存取。
解決方案:
從版本3.3.0 開始,C 中的頭檔google/protobuf/util 中引入了用於讀寫分隔訊息的等效函數/delimited_message_util .h。這些函數是:
注意:
由C 和Java protobuf 庫的原作者提供的替代實現提供了優化不存在於官方庫實現中。如下所示,此實作可以防止輸入 64MB 後出現潛在故障,同時仍強制單一訊息實施 64MB 限制:
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; }
以上是如何用 C 語言實作 Java Protocol Buffers 定界 I/O 功能?的詳細內容。更多資訊請關注PHP中文網其他相關文章!