c#
c#的protobuf我使用的是protobuf-net版本
安装方法如下:
c#中使用probuf只需要为每种数据类型定义一个类,就可以实现数据的序列化,基本示例代码如下:
using System;
using ProtoBuf;
using System.IO;
class Program
{
static void Main(string[] args)
{
MemoryStream ms = new MemoryStream();
NetModel nm = new NetModel() { ID = 1, Commit = "LanOu", Message = "Unity" };
//序列化对象
Serializer.Serialize<NetModel>(ms, nm);
byte[] temp = ms.ToArray();
MemoryStream ms2 = new MemoryStream(temp);
NetModel nm2 = Serializer.Deserialize<NetModel>(ms2);
Console.WriteLine($"{nm2.ID} {nm2.Commit} {nm2.Message}");
Console.ReadKey();
}
}
//添加特性,表示可以被ProtoBuf工具序列化
[ProtoContract]
public class NetModel
{
//添加特性,表示该字段可以被序列化,1可以理解为下标
[ProtoMember(1)]
public int ID;
[ProtoMember(2)]
public string Commit;
[ProtoMember(3)]
public string Message;
}
python
python2.7使用protobuf需要先安装protobuf库,安装命令: pip install protobuf
然后安装.proto文件的编译工具 ,安装命令: pip install grpcio-tools
然后编写自己的数据格式,示例如下:
#文件名 student.proto
syntax = "proto2";
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
执行编译命令: python -m grpc_tools.protoc -I ./ --python_out=./ student.proto
最后在python中protobuf的基本用法如下:
import student_pb2
people = student_pb2.Person()
people.name = "go"
people.id = 233
people.email = "fadfadsfa"
data = people.SerializeToString()
people2 = student_pb2.Person()
people2.ParseFromString(data)
print(people2.name,people2.id,people2.email)