Protobuf的强大我就不多介绍了,问度娘,会有很多说明的,今天配置了一下Unity里使用Protobuf,
写.proto文件:
ID文件:
enum MSGID
{
CSID_C2L_LOGINSERVER = 1020; //请求登陆
CSID_L2C_LOGINSERVER = 1021; //返回登陆结果
}
Data文件:
message MSG_C2L_LOGINSERVER
{
required string account = 1; //账号
required string password = 2; //密码
}
message MSG_L2C_LOGINSERVER
{
required int32 ret = 1; //0成功,否则为错误号
}
接着使用工具生成C#代码文件,工具怎么生成,哪里来的,我就略过了,这里提供下载地址: Protobuf编译C++和C#文件
把生成出来的C#文件拷贝的工程目录下,再把Google.ProtocolBuffers.dll(在Protobuf编译C++和C#文件包里有)拷贝到工程的dll目录下面,重新编译,
重新打开VS,可以看到VS工程引用下面有Google.ProtocolBuffers就说明没有问题。
最后就是调用,代码如下:
//声明
DotaMsgData.MSG_C2L_LOGINSERVER.Builder msgLogin = new DotaMsgData.MSG_C2L_LOGINSERVER.Builder();
msgLogin.SetAccount("test");
msgLogin.SetPassword("123456");
//使用Google.ProbobufBuffes
IMessage msg = msgLogin.Build();
//转成流
MemoryStream sendstream = new MemoryStream();
msg.WriteTo(sendstream);
public T StreamToMsg<T>(MemoryStream ms) where T : class, IMessage
{
Type type = typeof(T);
g_obj.SetValue(ms.ToArray(), 0);
MethodInfo method = type.GetMethod("ParseFrom", g_types);
return (T)method.Invoke(null, g_obj);
}
private object[] g_obj = new object[1];
private static Type[] g_types = new Type[] { typeof(byte[]) };
然后调用上面那个函数:
DotaMsgData.MSG_C2L_LOGINSERVER msgpre = StreamToMsg<DotaMsgData.MSG_C2L_LOGINSERVER>(sendstream);
Debug.Log("ParseRet, pssword: " + msgpre.Password);
Debug.Log("ParseRet, account: " + msgpre.Account);
从上面可以看出,Protobuf在C#中的写法和C++中的写法不太一样, C#里面需要通过DotaMsgData.MSG_C2L_LOGINSERVER.Builder来处理对象。
上面的方法只能在安卓和pc上面用,如果想要在ios上用的话可以参考下面这种方法
生成Dll的方式放入工程调用,参考资料:在ios android设备上使用 Protobuf (使用dll方式)