protocol-buffers

   https://developers.google.cn/protocol-buffers/

google发明的跨语言的数据交换格式,

他支持Java, Python, Objective-C, and C++

 proto3开始增加支持Dart, Go, Ruby, and C# 等

1.数字

  • 1-15 需要一个字节编码,1-15应该定义频繁使用的传输字段。如果不是频繁使用的,尽量把1-15预留出来
  • 16-2047需要两个字节
  • 最大能到2的29次方
  • 不能使用19000 到 19999

2.注释

// 单行

/*
多行
*/

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

3.保留字段

// The request message containing the user's name.
message HelloRequest {
  reserved 2, 15, 9 to 11; //保留数字
  reserved "foo", "bar";// 保留名称
  string foo = 12;
}

如果使用了保留的数字或名称编译时会报错

4.每种语言编译成什么文件

When you run the protocol buffer compiler on a , the compiler generates the code in your chosen language you'll need to work with the message types you've described in the file, including getting and setting field values, serializing your messages to an output stream, and parsing your messages from an input stream..proto

For C++, the compiler generates a and file from each , with a class for each message type described in your file..h.cc.proto
For Java, the compiler generates a file with a class for each message type, as well as a special classes for creating message class instances..javaBuilder
Python is a little different – the Python compiler generates a module with a static descriptor of each message type in your , which is then used with a metaclass to create the necessary Python data access class at runtime..proto
For Go, the compiler generates a file with a type for each message type in your file..pb.go
For Ruby, the compiler generates a file with a Ruby module containing your message types..rb
For Objective-C, the compiler generates a and file from each , with a class for each message type described in your file.pbobjc.hpbobjc.m.proto
For C#, the compiler generates a file from each , with a class for each message type described in your file..cs.proto
For Dart, the compiler generates a file with a class for each message type in your file..pb.dart

5.语言类型对照

[1]在 Java 中,未签名的 32 位和 64 位整数使用其签名的对数表示,顶部位仅存储在符号位中。

[2]在所有情况下,将值设置为字段将执行类型检查以确保其有效。

[3] 64 位或无符号 32 位整数在解码时始终表示为长,但如果在设置字段时给出 int,则可以是 int。在所有情况下,该值必须适合设置时表示的类型。参见 {2}。

[4] Python 字符串在解码时表示为单码,但如果给定了 ASCII 字符串(这可能会更改),则可以表示为 str。

[5]整数用于 64 位计算机,字符串用于 32 位计算机

6.默认值

  • 对于字符串,默认值为空字符串。
  • 对于字节,默认值为空字节。
  • 对于 bools,默认值为 false。
  • 对于数字类型,默认值为零。
  • 对于枚举,默认值是第一个定义的枚举值,该值必须为0
  • 对于消息字段,未设置该字段。它的确切值取决于语言
原文地址:https://www.cnblogs.com/buchizaodian/p/13378246.html