参考 https://blog.csdn.net/wangshubo1989/article/details/53437190
下载protobuf2.6.1 https://github.com/protocolbuffers/protobuf/releases/tag/v2.6.1 protobuf-2.6.1.zip
person.proto:如下:
package tutorial;
message Person {
required string name = 1;
required int32 age = 2;
optional string email = 3;
}
打开 : E:\canDel\protobuf-2.6.1\vsprojects\protobuf.sln 把所有工程编译,然后:E:\canDel\protobuf-2.6.1\vsprojects\x64\Release>protoc -I=E:\canDel\test_protobuf --cpp_out=E:\canDel\test_protobuf E:\canDel\test_protobuf\person.proto,如下图所示:
下面使用这个:
将person.pb.cc person.pb.添加进工程中。
工程添加VC目录:;..\..\protobuf-2.6.1\src\;
添加VC库:;..\..\protobuf-2.6.1\vsprojects\x64\Release; ;libprotobuf.lib;libprotoc.lib;
下面是main源码:
// test_protobuf.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "person.pb.h"
using namespace std;
using namespace tutorial;
int main()
{
Person person;
person.set_name("liyifeng");
person.set_age(26);
person.set_email("[email protected]");
cout << person.name() << endl;
cout << person.age() << endl;
cout << person.email() << endl;
//序列化 b
tutorial::Person* p = new tutorial::Person();
p->set_name("liyifeng");
p->set_age(26);
p->set_email("[email protected]");
int buffsize = p->ByteSize();
void* buff = malloc(buffsize);
p->SerializeToArray(buff, buffsize);
//序列化 e
//反序列化 b
tutorial::Person personx;
int length = 100 ;
personx.ParseFromArray(buff, length);
string name = personx.name();
int age = personx.age();
string email = personx.email();
//反序列化 e
getchar();
system("pause");
return 0;
}