protocol buffer是google的一个开源项目,它是用于结构化数据串行化的灵活、高效、自动的方法。相对XML、JSON,它更简单高效。

接下来我们来配置下windows下环境:

1、由CMake 生成VS工程:

Google Protocol Buffer_protobuf

注意要屏蔽掉protobuf_BUILD_TESTS,否则会报找不到gtest的问题;

此外还有一点要注意,就是protobuf的版本的选择,最新的版本很多语法基于C++11的,如果你的vs版本较低,就会出现问题,我选用的是3.1版本的+vs2013.

2、打开vs工程,编译链接库和protoc.exe工具:

一键编译下去,然后在我们工程目录下的Debug目录下就会生成我们想要的库和工具。

Google Protocol Buffer_#include_02

3、编写proto文件,test.proto:

//test.proto
syntax = "proto3";

package tutorial;

message Person {
string name = 1;
int32 id = 2;
string email = 3;

enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}

message PhoneNumber {
string number = 1;
PhoneType type = 2 ;
}

repeated PhoneNumber phones = 4;
}

message AddressBook {
repeated Person people = 1;
}

接下来用第2部生成的protoc.exe工具,生成代码中可调用的接口:

protoc.exe -I=./ -cpp_out=./ test.proto 

然后就会生成test.pb.h,test.pb.cc.

4、hello world

测试工程:

#include <iostream>
#include <fstream>
#include "test.pb.h"
#pragma comment(lib, "libprotobufd.lib")

int main(int argc, void* argv[])
{
tutorial::Person msg1;
msg1.set_id(101);
msg1.set_name("hello world!");
std::fstream out("User.pb", std::ios::out | std::ios::binary | std::ios::trunc);
msg1.SerializeToOstream(&out);
out.close();

tutorial::Person msg2;
std::fstream in("User.pb", std::ios::in | std::ios::binary);
if (!msg2.ParseFromIstream(&in)) {
std::cerr << "Failed to parse User.pb." << std::endl;
exit(1);
}

std::cout << msg2.id() << std::endl;
std::cout << msg2.name() << std::endl;
std::cout << msg2.email() << std::endl;


getchar();
return 0;
}

使用第2步中生成的 libprotobufd.lib ,配置好工程,编译输出如下:

Google Protocol Buffer_github_03

注意,在配置工程的时候不要忘记加上PROTOBUF_USE_DLLS这个宏,否则链接的时候会报如下的错误:

Google Protocol Buffer_ios_04