参考 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,如下图所示:

protobuf使用

下面使用这个:

protobuf使用

protobuf使用

将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;
}

 

相关文章:

  • 2021-08-17
  • 2021-05-21
  • 2021-10-12
  • 2022-02-13
  • 2021-05-28
  • 2022-01-09
猜你喜欢
  • 2021-11-03
  • 2021-04-06
  • 2021-10-11
  • 2021-09-08
  • 2021-11-26
相关资源
相似解决方案