> 백엔드 개발 > C++ > C에서 Java 프로토콜 버퍼 구분 I/O 기능을 달성하는 방법은 무엇입니까?

C에서 Java 프로토콜 버퍼 구분 I/O 기능을 달성하는 방법은 무엇입니까?

Barbara Streisand
풀어 주다: 2024-12-05 02:32:09
원래의
1030명이 탐색했습니다.

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

Java 프로토콜 버퍼 구분 I/O 함수에 대한 C 등가물

문제:
개발자가 여러 프로토콜 버퍼 메시지를 읽고 쓰려고 시도하는 경우 C 및 Java의 파일에서 Java에서 사용할 수 있는 "구분된" I/O 기능을 사용하면 문제가 발생할 수 있지만 C에서는 접근 가능한 것처럼 보입니다.

해결책:
버전 3.3.0부터 구분된 메시지를 읽고 쓰는 것과 동등한 기능이 C 헤더 파일 google/protobuf/에 도입되었습니다. 유틸리티/delimited_message_util.h. 이러한 함수는 다음과 같습니다.

  • writeDelimitedTo(): ​​google::protobuf::io::ZeroCopyOutputStream에 구분된 메시지를 씁니다.
  • readDelimitedFrom(): google::protobuf::io::ZeroCopyOutputStream에 구분된 메시지를 씁니다. google::protobuf::io::ZeroCopyInputStream.

참고:
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 프로토콜 버퍼 구분 I/O 기능을 달성하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿