protobuf定义了一种数据交换格式,具有性能高,有代码生成机制,兼容性好等优点,广泛应用在游戏开发领域,常常用它来定义客户端与服务器之间的通信协议。
常用接口:
序列化与反序列化相关:
bool SerializeToArray(void* data, int size) const;
bool ParseFromArray(const void* data, int size);
bool SerializeToString(string* output) const;
bool ParseFromString(const string& data);
bool SerializeToFileDescriptor(int file_descriptor) const;
bool ParseFromFileDescriptor(int file_descriptor);
bool SerializeToOstream(ostream* output) const;
bool ParseFromIstream(istream* input);
size相关:
message test_proto {
optional uint32 test = 1;
repeated uint32 test2 = 2;
}
test_proto msg;
msg.set_test(2);
for (int i = 1; i < 10; ++i) {
msg.add_test2(i);
}
(1)msg.test2_size()
test2字段的大小
(2)msg.ByteSize()
msg消息的大小
(3)msg.GetCachedSize();
string buf;
int size = address_book.ByteSize();
void *buffer = malloc(size);
msg.SerializeToString(&buf); 或者msg.SerializeToArray(buffer, size);
这个时候使用msg.GetCachedSize();可以获取msg消息的大小,与(2)求出来的大小一样。
设置与获取数据相关:
message test_proto2 {
optional uint32 test = 1;
repeated uint32 test2 = 2;
optional test_proto test3 = 3;
repeated test_proto test4 = 4;
}
test_proto2 msg2;
1. 被optional关键字修饰
(1) 系统类型
设置:
msg2.set_test(2);
获取:
uint32_t tmp = msg2.test();
(2) 自定义类型
设置:
auto tmp = msg2.mutable_test3();
tmp->set_test(3);
获取:
auto &it = msg2.test3();
uint32_t tmp = it.test();
2. 被repeated关键字修饰
(1) 系统类型
设置:
for (int i = 1; i < 10; i+) {
msg2.add_test2(2);
}
获取:
for (auto &it : msg2.test2()) {
tmp_vec.push_back(it);
}
(2) 自定义类型
设置:
auto tmp = msg2.add_test4();
tmp->set_test(2);
获取:
for (int i = 0; i < msg2.test4_size(); ++i) {
auto &tmp = msg2.test4(i);
uint32_t value = tmp.test();
}
或者:
for (auto &it : msg2.test4()) {
uint32_t tmp = it.test();
}
参考资料:
https://blog.youkuaiyun.com/tennysonsky/article/details/73920767
https://cloud.tencent.com/developer/article/1504465
https://blog.youkuaiyun.com/sealyao/article/details/6940245
https://blog.youkuaiyun.com/tennysonsky/article/details/73810180
https://blog.youkuaiyun.com/benny5609/article/details/7592301
https://blog.youkuaiyun.com/linxinfa/article/details/90515593
本文深入探讨了protobuf这一高效的数据交换格式,介绍了其在游戏开发领域的应用,详细讲解了protobuf的序列化与反序列化接口,以及如何通过protobuf进行数据的大小计算和数据操作,为读者提供了丰富的代码示例。
1347

被折叠的 条评论
为什么被折叠?



