Overview
这一节给出C++代码调用protoc的例子。
Compiling dependent packages
对于C++代码,需要确定protobuf对应的include或lib查找路径,以及依赖库名称。对应的命令:
$ pkg-config --cflags --libs protobuf
-D_THREAD_SAFE -I/usr/local/include -L/usr/local/lib -lprotobuf -D_THREAD_SAFE
$
或
$ pkg-config --cflags --libs protobuf
-pthread
$
Write / Serialize
代码中给出生成命令、生成文件的内容。
/*
g++ writer.cpp helloworld.pb.cc -I/usr/local/include -L/usr/local/lib -lprotobuf -pthread -lpthread
$ hexdump -C log
00000000 08 65 12 05 68 65 6c 6c 6f |.e..hello|
00000009
$
*/
#include <iostream>
#include <fstream>
#include "helloworld.pb.h"
int main(void)
{
helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
// Write the new address book back to disk.
std::fstream output("./log", std::ios::out | std::ios::trunc | std::ios::binary);
if (!msg1.SerializeToOstream(&output)) {
std::cerr << "Failed to write msg." << std::endl;
return -1;
}
return 0;
}
Read / Deserialize
/*
g++ reader.cpp helloworld.pb.cc -I/usr/local/include -L/usr/local/lib -lprotobuf -pthread -lpthread
$ g++ reader.cpp helloworld.pb.cc -I/usr/local/include -L/usr/local/lib -lprotobuf -pthread -lpthread
$ ./a.out
101
hello
$
*/
#include <iostream>
#include <fstream>
#include "helloworld.pb.h"
void ListMsg(const helloworld & msg)
{
std::cout << msg.id() << std::endl;
std::cout << msg.str() << std::endl;
}
int main(int argc, char* argv[])
{
helloworld msg;
std::fstream input("./log", std::ios::in | std::ios::binary);
if (!msg.ParseFromIstream(&input)) {
std::cerr << "Failed to parse address book." << std::endl;
return -1;
}
ListMsg(msg);
return 0;
}