Protocol Buffer (Unity3D & Golang

504 阅读1分钟

如何在Unity3D和Golang中,使用ProtocolBuffer

首先安装ProtocolBuffer,并正确设置目录。

CSharp

安装Unity3D的DLL

  1. 下载: github.com/protocolbuf…
  2. 进入目录 csharp/src,找到Google.Protobuf.sln,使用Rider进行生成
  3. 将生成后的DLL拷贝至Unity/Assets目录下,让Unity调用

写proto文件

syntax = "proto3";
package test;

import "google/protobuf/timestamp.proto";
option csharp_namespace = "test";

message TT 
{
    string name = 1;
}

编译proto文件

  1. 下载: github.com/protocolbuf…
  2. 将bin和includes拷贝到/usr/local/bin/
  3. bin/protoc chmod 775
  4. 在proto文件目录下,执行: protoc --csharp_out=. test.proto

序列化和反序列化

developers.google.com/protocol-bu… blog.yowko.com/csharp-prot…

序列化

需加入 using Google.Protobuf;

  1. byte[]
private static byte[] GetByteArray(Person person)
{
	using (var ms = new MemoryStream())
	{
		person.WriteTo(ms);
		return ms.ToArray();
    
	}
}
  1. ByteString
private static ByteString GetByteString(Person person)
{
	using (var ms = new MemoryStream())
	{
		person.WriteTo(ms);
		return ByteString.CopyFrom(ms.ToArray());
	}
}

  1. Stream
private static MemoryStream GetStream(Person person)
{
	var ms = new MemoryStream();
	person.WriteTo(ms);
	return ms;
}

反序列化

  1. byte[]
private static Person GetPersonFromByteArray(byte[] bytes)
{
	return Person.Parser.ParseFrom(bytes);
}
  1. ByteString
private static Person GetPersonFromByteString(ByteString byteString)
{
	return Person.Parser.ParseFrom(byteString);   
}
  1. Stream
private static Person GetPersonFromStream(Stream ms)
{
	ms.Seek(0, SeekOrigin.Begin);
	return Person.Parser.ParseFrom(ms);
}

Golang

安装Golang的protobuf包

go install google.golang.org/protobuf/cmd/protoc-gen-go@lates

写proto文件

syntax = "proto3";

package test1;

  

import "google/protobuf/timestamp.proto";

option go_package = "./;test1"; // 注意这个路径

  

message TT

{

string name = 1;

}

编译

protoc --proto_path=. --go_out=. --go_opt=paths=source_relative test1.proto

序列化和反序列化

developers.google.com/protocol-bu…

需要

import (  
   "google.golang.org/protobuf/proto"  
   "test1/test1")

序列化

x := &test1.TT{}  
x.Name = "a"  
println(x.Name)  
d, e := proto.Marshal(x)  
if e != nil {  
   println(e.Error())  
}  
println(len(d))

反序列化

y := &test1.TT{}  
proto.Unmarshal(d, y)  
println(y.Name)