ホームページ >バックエンド開発 >C++ >C で Java プロトコル バッファ区切り I/O 機能を実現するにはどうすればよいですか?

C で Java プロトコル バッファ区切り I/O 機能を実現するにはどうすればよいですか?

Barbara Streisand
Barbara Streisandオリジナル
2024-12-05 02:32:091021ブラウズ

How to Achieve Java Protocol Buffers Delimited I/O Functionality in C  ?

C の Java プロトコル バッファー区切り I/O 関数に相当するもの

問題:
開発者が複数のプロトコル バッファー メッセージの読み取りと書き込みを試行しているC と Java の両方のファイルからの場合、Java では使用できる「区切り文字付き」I/O 関数を使用すると問題が発生する可能性があります。 C でアクセスできるようです。

解決策:
バージョン 3.3.0 では、ヘッダー ファイル google/protobuf/ 内の区切りメッセージの読み取りと書き込みに相当する関数が C に導入されました。 util/delimited_message_util.h。これらの関数は次のとおりです:

  • writeDelimitedTo(): 区切り文字で区切られたメッセージを google::protobuf::io::ZeroCopyOutputStream に書き込みます。
  • readDelimitedFrom(): 区切り文字で区切られたメッセージを google::protobuf::io::ZeroCopyOutputStream から読み取ります。 google::protobuf::io::ZeroCopyInputStream.

注:
C および Java protobuf ライブラリの元の作成者によって提供される代替実装は、最適化を提供します。公式ライブラリ実装には存在しません。以下に示すこの実装では、個々のメッセージに 64 MB の制限を適用しながら、64 MB の入力後の潜在的な障害を防止します。

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 プロトコル バッファ区切り I/O 機能を実現するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。