新建尾缀.proto的文件
syntax = "proto3"; //版本 message Ctest2{ int32 j = 1; string str = 2; } message Ctest{ int32 i = 1; string str = 2; repeated Ctest2 p = 3; // 嵌套message; repeated关键字,增加count计数,(类似于数组)
}
编译proto文件,生成.cc和.h文件
protoc -I=./ --cpp_out=./ *.proto
测试程序
#include <iostream> #include "test.pb.h" int main() { Ctest test; Ctest2 *test2 = test.add_p(); // test.add_p()返回一个指针,指向成员p;
std::string str1;
test.set_i(10);
test.set_str("...");
test2->set_j(111); // 通过指针给test.p的成员赋值
test2->set_str("!!!");
std::cout << "Ctest::i = " << test.i() << std::endl;
std::cout << "Ctest::str = " << test.str() << std::endl;
std::cout << "Ctest::Ctest2::j = " << test2->j() << std::endl;
std::cout << "Ctest::Ctest2::str =" << test2->str() << std::endl;
test.SerializeToString(&str1); // 序列化
test.ParseFromString(str1); // 反序列化
return 0;
}
编译:
g++ -std=c++11 test.pb.cc main.cpp test.pb.h -o main -lprotobuf
运行结果:
[root@localhost test]# ./main Ctest::i = 10 Ctest::str = ... Ctest::Ctest2::j = 111 Ctest::Ctest2::str =!!!