Protobuf的编译
Protobuf的下载与编译
编译错误:
1 hash_map需要宏 _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS;
2 _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING;
3 ETC宏 SPEPARATOR宏 注意加空格
4 修改编译,每次只编译1个项目
Protobuf的使用
数据封包,解包,打包是快捷,高效的
这个东西是比较容易修改的
与语言无关、平台无关、可扩展的
用于序列化结构化数据的
效率高
Protobuf的使用
将生成的lib复制到当前目录
写一个协议文件
//tianchen.proto
message EmbeddedMessage{
required uint32 nSubCmd=1;
required string strParams=2;
}
message TianChenMsg{
//required optional repeated(字段规则) 可以迭代
required uint32 nCmd =1 [default=0];
required string strData=2;
optional EmbeddedMessage subMsg=3;
}
生成相关代码 然后添加进去,
.\protoc.exe -I. --cpp_out=. tianchen.proto
然后从NetGut下载Protobuf的相关文件,进行编写代码
代码
#include <iostream>
#include "tianchen.pb.h"
#pragma comment(lib,"libprotobuf.lib")
#pragma comment(lib,"libprotobuf-lite.lib")
#pragma comment(lib,"libprotoc.lib")
int main()
{
TianChenMsg msg;
msg.set_ncmd(0);
msg.set_strdata("hello wolrd");
EmbeddedMessage* sub=new EmbeddedMessage();
sub->set_nsubcmd(1);
sub->set_strparams("tian chen");
msg.set_allocated_submsg(sub);
msg.SerializePartialToOstream(&std::cout);
std::string result = msg.SerializeAsString();//序列化
//std::string result = msg.SerializePartialAsString();
//std::cout << result << std::endl;
//网络发送
TianChenMsg msg2;
msg2.ParseFromString(result);//反序列化
std::cout<<std::endl << "cmd:" << msg2.ncmd() << std::endl;
}