proto 文件格式
syntax = "proto3"; // 指定版本信息,不指定会报错
packag pb; // 后期生成go文件的包名
// message为关键字,作用为定义一种消息类型
message Person{
string name = 1; // 名字
int32 age = 2 ; // 年龄
}
enum test{
int32 age = 0;
}
protobuf 和 C++
- 没有设置默认值,也会有默认值,例如:布尔类型(bool)默认为 false。
- 定义类型,唯一的标识符,范围为1到2^29 - 1
- 导入头文件,首先是包名作为namespace,声明变量
pb::Person person; - proto2中
required optional repeated 必须写,不写编译不通过 - proto3中只有
repeated可用,写了其他的,编译不通过 - required:必须包含
optional:可选包含
repeated:可以重复包含 - 若required写了,在序列化时候,会报错
- 常见使用方法
#include "person.pb.h"
#include
using namespace std;
int main() {
pb::Person person;
person.set_name("chang");
cout << person.name() << endl;
person.mutable_name()->assign("jiang");
cout << person.name() << endl;
pb::Person person1;
person.CopyFrom(person1);
person.mutable_name()->assign("da");
cout << person.name() << endl;
pb::Person::Student* student2 = person.add_s();
student2->set_id("fef");
student2 = person.add_s();
student2->set_id("fef");
cout << person.s_size() << endl;
cout << person.s(0).id() << endl;
cout << person.s(1).id() << endl;
person.add_s();
person.mutable_s(2)->set_id("e2");
cout << person.s_size() << endl;
cout << person.s(2).id() << endl;
std::string serialized_data;
person.SerializeToString(&serialized_data);
pb::Person new_person;
new_person.ParseFromString(serialized_data);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- proto编译成c++,
protoc --cpp_out=./ ./demo.proto - c++编译成执行文件
g++ test.cpp person.pb.cc -lprotobuf -pthread
protobuf 和 python
- 编译方式:
protoc --python_out=./ person.proto - 常见使用
import person_pb2
p = person_pb2.Person()
p.name = "fwef"
print(p.name)
serialized_data = p.SerializeToString()
new_person = person_pb2.Person()
new_person.ParseFromString(serialized_data)
常见C++报错一:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
参考文档
解决方案:
g++ test.cpp person.pb.cc -lprotobuf -pthread