ProtoBuf安装和使用简介

在前一篇文章中,对ProtoBuf做了一个基本介绍,这篇文章主要介绍ProtoBuf的安装和使用。

ProtoBuf的安装

安装ProtoBuf前需要先安装ProtoBuf的编译器和运行时环境。

对于C++使用者:由于ProtoBuf是用C++写的,因此你可以获取ProtoBuf的源码自己编译,而对于其他语言来说可以直接使用ProtoBuf已经编译好的Release版本直接进行安装和使用,相比来说使用Release版本会方便很多。

ProtoBuf在Git上的地址是:https://github.com/google/protobuf.git, 你可以clone源码然后按照ReadMe文件自己编译。

获取Release版本的地址是:https://github.com/google/protobuf/releases 你可以从这个地址下载你所需要的安装包,注意使用C++编程的话下载cpp的包,其他语言对应选择,本文介绍了Linux下安装和使用ProtoBuf.

1、下载ProtoBuf的压缩包protobuf-cpp-3.0.0-beta-3.tar.gz 随便哪个版本都行

     将安装包拷贝到你的Linux机器上,进入所在目录,利用tar命令将该文件解压缩到当前文件夹。

    加压后你可以再该目录下找到ReadME文件,这个文件就介绍了如何安装ProtoBuf,安装这部分基本是对该文件的一个中文翻译,英文水平好的可以直接参照该文件安装

2、安装ProtoBuf

   $ ./configure
   $ make
   $ make check
   $ sudo make install
   $ sudo ldconfig # refresh shared library cache.

进入你解压后的目录,依次执行以上命令,如果命令都执行成功,说明ProtoBuf安装成功。通常情况ProtoBuf都安装在/usr/local目录下,该目录下包含了ProtoBuf的头文件,静态库和动态库文件



如何使用ProtoBuf

ProtoBuf安装完成后,就可以按照上一篇文章介绍的步骤去使用ProtoBuf。(定义你自己的ProtoBuf源文件,用ProtoBuf编译器编译该源文件)

在本节内容中引用了Google官网中关于ProtoBuf使用的电话本的例子来介绍ProtoBuf的使用。


定义一个ProtoBuf源文件,Person.pro

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 phone = 4;
}

message AddressBook
{
	repeated Person person =1;
}


可以看到该文件中,包含了ProtoBuf结构的嵌套以及使用另外一种自定义的数据类型,Person结构中包含了一个Person联系人的基本信息,包括name, id ,email PhoneNumber

而PhoneNumber又是一个ProtoBuf的结构定义,某个属性被标注为repeated意味着编译后生成的Person对象中可以包含一个或者多个PhoneNumber也就是电话号码,而结构AddressBook中有包含了多个联系人Person 这个不难理解,跟我们实际手机联系人信息差不多,电话本中包含了多个联系人,每个联系人可以有多个电话号码,如家庭电话,手机,工作电话。


编译该源文件

 进图到源文件目录编译该源文件 protoc -I=。   --cpp_out=.  Person.pro

编译后生成Person.proto,pb.h 和Person.pro.pb.cc文件,这两个文件包含了Person以及AddressBook的类,以及对应操作类的方法,在你使用者这些类必须包含头文件,最终可执行文件也必须将cc文件也编译进去。

下面展示使用Person的代码。

add_person.cpp 展示了如何设置一个联系人的各个字段的信息,并且最终序列化信息到文件中。

#include "Person.pro.pb.h"
#include <fstream>
#include <iostream>
using namespace std;

void PromptForAddress(tutorial::Person*);

int main(int argc, char* argv[])
{
	GOOGLE_PROTOBUF_VERIFY_VERSION;
	if(2 != argc)
	{
		//必须指定电话本名称才执行程序
	    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
	    return -1;
	}

	tutorial::AddressBook address_book;

	fstream in("ADDRESS_BOOK_FILE", ios::binary | ios::in);
	if(!in)
	{
		cerr << "open file ADDRESS_BOOK_FILE failed!\n";
		return -1;
	}
	
	if(!address_book.ParseFromIstream(&in))
	{
		cerr << "Parse File ADDRESS_BOOK_FILE failed!\n";
		return -1;
	}
	
	in.close();
	//增加一个Person,可通过多次调用该接口增加联系人
	//具有repeated的属性可通过add_fieldname方法增加一个属性
	PromptForAddress(address_book.add_person());

	fstream out("ADDRESS_BOOK_FILE", ios::binary | ios::out | ios::trunc);
	if(!address_book.SerializeToOstream(&out))
	{
		cerr << "Failed to Write Address Book!\n";
		return -1;	
	}

	//可选的,回收所有ProtoBuf分配的对象
	google::protobuf::ShutdownProtobufLibrary();
	return 0;
}


void PromptForAddress(tutorial::Person* person)
{
	cout<<"Enter a Person ID number: ";
	int id;
	cin >> id;
	person->set_id(id);
	/*忽略CIN的前256个字符,或者忽略CIN的换行符之前的字符,包括换行符
	这样的话不会将换行符之前的其他类型的数据保留在输入缓冲中	
	*/
	cin.ignore(256, '\n');
	cout<<"Enter name: ";
	getline(cin, *person->mutable_name());

	cout<< "Enter email address (blank for none): ";
	string email;
	getline(cin,email);
	if(!email.empty())
		person->set_email(email);
	while(true)
	{
		cout<<"Enter a phone number (or leave blank to finish): ";
		string number;
		getline(cin, number);
		if(number.empty())
			break;
		tutorial::Person::PhoneNumber* phone_number = person->add_phone();
		phone_number->set_number(number);

		cout<<"Is this a mobile, home, or work phone? ";
		string type;
		getline(cin, type);
		if(type == "mobile")
			phone_number->set_type(tutorial::Person::MOBILE);
		else if( type == "home")
			phone_number->set_type(tutorial::Person::HOME);
		else if (type == "work")
			phone_number->set_type(tutorial::Person::WORK);
		else
		{
			cout << "Unknown phone type.  Using default." << endl;
			phone_number->set_type(tutorial::Person::HOME);
		}
		
	}
	
}

list_cpp展示了如何从文件中读取ProtoBuf序列化的信息

#include "Person.pro.pb.h"
#include <iostream>
#include <fstream>

using namespace std;
void ListPeople(const tutorial::AddressBook& address_book);
int main(int argc, char * argv[])
{
	if(2!=argc)
	{
	    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
	    return -1;
	}

	fstream in("ADDRESS_BOOK_FILE", ios::in | ios::binary);
	tutorial::AddressBook address_book;
	if(!address_book.ParseFromIstream(&in))
	{
	    cerr << "Parse Input File failed!"<< endl;
	    return -1;
	}

	ListPeople(address_book);
	google::protobuf::ShutdownProtobufLibrary();
	return 0;
}

void ListPeople(const tutorial::AddressBook& address_book)
{
	//fieldName_size方法返回具有repeated属性的个数
	for(int i=0; i< address_book.person_size();i++)
	{
		const tutorial::Person& person = address_book.person(i);
		cout<<"Person ID: "<<person.id();
		cout<<"Name: "<<person.name();
		cout<<"Email: "<<person.email();
		
		for(int j=0; j< person.phone_size();j++)
		{
			const tutorial::Person::PhoneNumber& phone_number = person.phone(j);
			switch(phone_number.type())
			{
		        case tutorial::Person::MOBILE:
		          cout << "  Mobile phone #: ";
		          break;
		        case tutorial::Person::HOME:
		          cout << "  Home phone #: ";
		          break;
		        case tutorial::Person::WORK:
		          cout << "  Work phone #: ";
		          break;
			}
			cout<<phone_number.number()<<endl;	
		}
		
	}
}

因为是在Linux下运行的代码,因此写了一个makefile 文件来编译。

test:add_people list_people

add_people:add_person.cpp protoMid
	c++  add_person.cpp Person.pro.pb.cc -o add_people `pkg-config --cflags --libs protobuf`

list_people: list_person.cpp protoMid	
	c++  list_person.cpp Person.pro.pb.cc -o list_people `pkg-config --cflags --libs protobuf`	
protoMid: Person.pro
	protoc -I=. --cpp_out=. ./Person.pro
	
clean:
	rm -f add_people list_people protoMid
	rm -f Person.pro.pb.cc Person.pro.pb.h


执行make后,生成add_people 和list_people两个可执行文件,可以先执行add_people文件增加联系人信息,再执行list_people显示所有联系人信息。


tips:

我在写makefile编译整个源文件时遇到了几个问题,一个是makefile中并没有显示的指定 -i -l 指定编译时需要的头文件地址和链接时需要指定的库文件地址,因此编译链接失败了,有两个方法可以解决该问题,一个是通过-i -l参数指定需要的头文件和库文件地址,另外一个是通过pkg-config 工具, 该工具通过PKG_CONFIG_PATH环境变量指定的地址去找.pc文件,该文件记录了ProtoBuf安装时头文件和库文件所在的目录。 

相比来说,第二种方法要方便很多,但是要注意的是要讲PKG_CONFIG_PATH环境变量设置到正确的地址,否则编译也会失败

$export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig/

导出后,编译成功。


本文仅介绍了基本的ProtoBuf的安装和使用过程,对于入门的人来说本文应该能够让读者明白怎么去使用ProtoBuf结构化数据,但对于更加详细的本文没有提及,比如说ProtoBuf2和ProtoBuf3的区别,定义.proto文件的详细语法等,需要了解的可以参考google官方文档










猜你喜欢

转载自blog.csdn.net/hailong0715/article/details/52057873