当前位置:首页 > Windows程序 > 正文

C#下使用protobuf(Google Protocol Buffers)

2021-03-27 Windows程序

        Protobuf是google提供的一个开源序列化框架,类似于XML,JSON这样的数据表示语言,其最大的特点是基于二进制,因此比传统的XML表示高效短小得多。除了比Json、XML有速度上的优势和使用上的方便外,protocolbuf还可以做到向前兼容和向后兼容。

        protobuf 虽然只支持JAVA、C++和Pyton,但protobuf社区的protobuf.net组件让protobuf可以支持更多的语言,其中就包括了C#。


protobuf协议

定义protobuf协议必须创建一个以.proto为后缀的文件,以本篇 创建了一个名为myproto.proto的文件,如下:


package ProtoTest; message TestInfo{ required string test = 1; optional int32 num = 2; } message Msg{ required int32 id = 1; optional TestInfo msg = 2; optional string str = 3 [defalut="Test String"]; }


package在Java里面代表这个文件所在的包名,在c#里面代表该文件的命名空间,message代表一个类, required 代表该字段必填,optional 代表该字段可选,并可以为其设置默认值,string的默认值格式为[defalut="字符串"]  整型的默认值格式为[defalut=23333]

下面是protobuf在.proto文件中的字段类型转换表:



.proto Type

 

Notes

 

C++ Type

 

Java Type

 

Python Type[2]

 

double

 

double

 

double

 

float

 

float

 

float

 

float

 

float

 

int32

 

Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.

 

int32

 

int

 

int

 

int64

 

Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.

 

int64

 

long

 

int/long[3]

 

uint32

 

Uses variable-length encoding.

 

uint32

 

int[1]

 

int/long[3]

 

uint64

 

Uses variable-length encoding.

 

uint64

 

long[1]

 

int/long[3]

 

sint32

 

Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.

 

int32

 

int

 

int

 

sint64

 

Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.

 

int64

 

long

 

int/long[3]

 

fixed32

 

Always four bytes. More efficient than uint32 if values are often greater than 228.

 

uint32

 

int[1]

 

int

 

fixed64

 

Always eight bytes. More efficient than uint64 if values are often greater than 256.

 

uint64

 

long[1]

 

int/long[3]

 

sfixed32

 

Always four bytes.

 

int32

 

int

 

int

 

sfixed64

 

Always eight bytes.

 

int64

 

long

 

int/long[3]

 

bool

 

bool

 

boolean

 

boolean

 

string

 

A string must always contain UTF-8 encoded or 7-bit ASCII text.

 

string

 

String

 

str/unicode[4]

 

bytes

 

May contain any arbitrary sequence of bytes.

 

string

 

ByteString

 

str


 

如何编译proto文件

在windows如何下载并编译protobuff,这部分参考博客:

github仓库地址:https://github.com/google/protobuf 

Google下载protobuff下载地址:https://developers.google.com/protocol-buffers/docs/downloads

在解压后的文件夹中,打开vsprojects目录,目录中的文件如图所示:

技术分享


技术分享


技术分享


温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68677.html