protobuf基本使用

文章链接:http://www.liuschen.com

下载protobuf,安装都是很简单的步骤,如果想要将安装文件安装到特定目录,需要在configure的时候加入具体的路径参数

./configure --prefix=/home/myprotobuf(自己指定的路径)

使用:

为了方便可以先将目录加入环境变量(这个是临时的):

exprot PATH=/home/myprotobuf/bin/:$PATH

将动态连接库的搜索路径加入到系统中(之后编译链接代码时会用到):

export LD_LIBRARY_PATH=/home/myprotobuf/lib:$LD_LIBRARY_PATH

首先,建一个文件protobuf_demo.proto,通过命令生成cc文件和头文件

protoc --cpp_out=. ./protobuf_demo.proto

protobuf_demo.proto记录了目标文件需要配置的元素

message protobuf_demo{

required int32 id = 1;
required string str = 2;
required string hello = 4;

}

然后再编写cpp文件并在文件中引用上面生成的C++头文件,我的文件如下

#include "protobuf_demo.pb.h"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>

#include <iostream>
#include <fcntl.h>

using namespace std;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;

int main(void)
{
protobuf_demo msg;
const char * filename = "some.prototxt";
int fd = open(filename,O_RDONLY);
if(fd == -1)
{
  cout << "File not found:" << filename << endl;
}
FileInputStream* input = new FileInputStream(fd);
bool success = google::protobuf::TextFormat::Parse(input,&msg);

cout << msg.id() << endl;
cout << msg.str() << endl;
cout << msg.hello() << endl;

}

编译生成可执行文件,然后通过该文件就可以读出当前文件加下some.prototxt的值

id: 1888
str: "192.168.0.1
hello: "haha"
Loading Disqus comments...
Table of Contents