The use of C + + / Python version of protobuf

Yngz_ Miao 2020-11-13 07:51:40
use python version protobuf


Last post explained protobuf The installation and .proto Definition of documents , And can generate C++ Version of .cc and .h file ,python Of .py file . So this article uses the generated data to access the classes , Serializing and deserializing objects .

Address of the first blog :【Protobuf】Protobuf Download installation and .proto File defines

Source code of this article github Address https://github.com/yngzMiao/yngzmiao-blogs/tree/master/2019Q4/20191228.


.proto File defines

syntax = "proto2";
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2;
}
message Address {
optional string country = 1;
optional string detail = 2;
}
message Person {
required int32 id =1;
required string name = 2;
optional int32 age = 3;
repeated string email = 4;
repeated PhoneNumber phone = 5;
optional Address address = 6;
}

C++ edition

Understanding data access classes

View the generated person.pb.h, Will see stay .proto Each specified in the file message All have a class . And each message Field of , Are defined as member variables in a class , It also provides some methods to modify these fields .

With the above .proto For example , Every one of them message All corresponding to a class , enumeration message It's also set up :

class PhoneNumber;
class Address;
class Person;
enum PhoneType {

MOBILE = 0,
HOME = 1,
WORK = 2
};

With Person For example , View several member variables in a class , Include message Fields defined in :

::std::string* name_;
::google::protobuf::int32 id_;
::google::protobuf::int32 age_;
::google::protobuf::RepeatedPtrField< ::std::string> email_;
::google::protobuf::RepeatedPtrField< ::PhoneNumber > phone_;
::Address* address_;

Yes message These fields in ,person.pb.h It also provides some methods for modification and other operations :

// required int32 id = 1;
inline bool has_id() const;
inline void clear_id();
static const int kIdFieldNumber = 1;
inline ::google::protobuf::int32 id() const;
inline void set_id(::google::protobuf::int32 value);
// required string name = 2;
inline bool has_name() const;
inline void clear_name();
static const int kNameFieldNumber = 2;
inline const ::std::string& name() const;
inline void set_name(const ::std::string& value);
inline void set_name(const char* value);
inline void set_name(const char* value, size_t size);
inline ::std::string* mutable_name();
inline ::std::string* release_name();
inline void set_allocated_name(::std::string* name);
// optional int32 age = 3;
inline bool has_age() const;
inline void clear_age();
static const int kAgeFieldNumber = 3;
inline ::google::protobuf::int32 age() const;
inline void set_age(::google::protobuf::int32 value);
// repeated string email = 4;
inline int email_size() const;
inline void clear_email();
static const int kEmailFieldNumber = 4;
inline const ::std::string& email(int index) const;
inline ::std::string* mutable_email(int index);
inline void set_email(int index, const ::std::string& value);
inline void set_email(int index, const char* value);
inline void set_email(int index, const char* value, size_t size);
inline ::std::string* add_email();
inline void add_email(const ::std::string& value);
inline void add_email(const char* value);
inline void add_email(const char* value, size_t size);
inline const ::google::protobuf::RepeatedPtrField< ::std::string>& email() const;
inline ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_email();
// repeated .PhoneNumber phone = 5;
inline int phone_size() const;
inline void clear_phone();
static const int kPhoneFieldNumber = 5;
inline const ::PhoneNumber& phone(int index) const;
inline ::PhoneNumber* mutable_phone(int index);
inline ::PhoneNumber* add_phone();
inline const ::google::protobuf::RepeatedPtrField< ::PhoneNumber >&
phone() const;
inline ::google::protobuf::RepeatedPtrField< ::PhoneNumber >*
mutable_phone();
// optional .Address address = 6;
inline bool has_address() const;
inline void clear_address();
static const int kAddressFieldNumber = 6;
inline const ::Address& address() const;
inline ::Address* mutable_address();
inline ::Address* release_address();
inline void set_allocated_address(::Address* address);

Yes message How to modify fields in , We can see the following rules roughly :

  • For basic proto type , Not repeated Field , Provides the same method name as the field name to get the contents of the field , Provides set Method to set the contents of the field ; and repeated Field , According to index To get the contents of a field , Provides add Method to add the contents of the field , Or designate index To carry out set;
  • For custom message type , Not repeated Field , Provides the same method name as the field name to get the contents of the field , Provides mutable Method to set the contents of the field ; and repeated Field , According to index To get the contents of a field , Provides add Method to add the contents of the field , Or designate index To carry out mutable.

serialize 、 Deserialization

For serialization and deserialization methods , It's all defined in message.h in :

bool ParseFromIstream(std::istream* input);
bool SerializeToOstream(std::ostream* output) const;
bool ParseFromString(const std::string& data);
bool SerializeToString(std::string* output) const;
bool SerializeToArray(void* data, int size) const;
std::string GetTypeName() const override;
size_t ByteSizeLong() const override;

example :

Instance content : take person Information utilization of protobuf, Serialization saved to file main.proto( there .proto Files are binary files , and .proto Structure declaration file only has the same suffix ) in ; Read the file again , Anti serialization into object printing .

#include <iostream>
#include <fstream>
#include "person.pb.h"
int main(int argc, char const *argv[])
{

Person *person = new Person();
person->set_id(1);
person->set_name("zhangsan");
person->set_age(18);
person->add_email("1.qq.com");
person->add_email("2.qq.com");
PhoneNumber *phone1 = person->add_phone();
phone1->set_number("123456");
phone1->set_type(PhoneType::HOME);
PhoneNumber *phone2 = person->add_phone();
phone2->set_number("234567");
phone2->set_type(PhoneType::MOBILE);
Address *address = person->mutable_address();
address->set_country("China");
address->set_detail("Jiangsu");
std::cout << "write to main.proto" << std::endl;
std::ofstream ofs;
ofs.open("main.proto", std::ofstream::binary);
person->SerializeToOstream(&ofs);
ofs.close();
std::cout << "read from main.proto" << std::endl;
Person *person_tmp = new Person();
std::ifstream ifs;
ifs.open("main.proto", std::ofstream::binary);
person_tmp->ParseFromIstream(&ifs);
std::cout << "id : " << person_tmp->id() << std::endl;
std::cout << "name : " << person_tmp->name() << std::endl;
std::cout << "age : " << person_tmp->age() << std::endl;
std::cout << "email : " << person_tmp->email(0) << " " << person_tmp->email(1) << std::endl;
std::cout << "phone : " << person_tmp->phone(0).number() << " " << person_tmp->phone(1).number() << std::endl;
std::cout << "address : " << person_tmp->address().country() << " " << person_tmp->address().detail() << std::endl;
return 0;
}

use CMakeLists.txt Compile and run :

yngzmiao@yngzmiao-virtual-machine:~/test/c++$ ./main
write to main.proto
read from main.proto
id : 1
name : zhangsan
age : 18
email : 1.qq.com 2.qq.com
phone : 123456 234567
address : China Jiangsu

Python edition

And C++ Similar version , Concrete person_pb2.py No specific data access classes are analyzed , Want to know , You can read it yourself .

serialize 、 Deserialization

For serialization and deserialization methods , It's easier :

str = obj.SerializeToString()
obj.ParseFromString(str)
obj.ByteSize()

example :

Instance content : take person Information utilization of protobuf, Serialization saved to file main.proto( there .proto Files are binary files , and .proto Structure declaration file only has the same suffix ) in ; Read the file again , Anti serialization into object printing .

# -*- coding:UTF-8 -*-
import os,sys
import proto_pb2.person_pb2 as person_proto
if __name__ == "__main__":
person = person_proto.Person()
person.id = 1
person.name = "zhangsan"
person.age = 18
person.email.append("1.qq.com")
person.email.append("2.qq.com")
phone1 = person.phone.add()
phone2 = person.phone.add()
phone1.number = "123456"
phone1.type = person_proto.PhoneType.HOME
phone2.number = "234567"
phone2.type = person_proto.PhoneType.MOBILE
addr = person.address
addr.country = "China"
addr.detail = "Jiangsu"
print("write to main.proto")
fw = open("main.proto", "w")
fw.write(person.SerializeToString())
fw.close()
print("read from main.proto")
fr = open("main.proto", "r")
data = fr.read()
person_tmp = person_proto.Person()
person_tmp.ParseFromString(data)
print("id : " + str(person_tmp.id))
print("name : " + str(person_tmp.name))
print("age : " + str(person_tmp.age))
print("email : " + str(person_tmp.email))
print("phone : " + str(person_tmp.phone))
print("address : " + str(person_tmp.address))
fr.close()

Run the script :

yngzmiao@yngzmiao-virtual-machine:~/test/python$ python main.py
write to main.proto
read from main.proto
id : 1
name : zhangsan
age : 18
email : [u'1.qq.com', u'2.qq.com']
phone : [number: "123456"
type: HOME
, number: "234567"
type: MOBILE
]
address : country: "China"
detail: "Jiangsu"

Binary

Compare the C++ Version and python Version generated main.proto Binary , Finally found , The two documents are as like as two peas. .

Open generated binary main.proto, You can see the content :

08 01 12 08 7A 68 61 6E 67 73 61 6E 18 12 22 08 31 2E
71 71 2E 63 6F 6D 22 08 32 2E 71 71 2E 63 6F 6D 2A 0A
0A 06 31 32 33 34 35 36 10 01 2A 0A 0A 06 32 33 34 35
36 37 10 00 32 10 0A 05 43 68 69 6E 61 12 07 4A 69 61
6E 67 73 75

What do these binaries mean , It will be introduced in the following blog .


Related reading

版权声明
本文为[Yngz_ Miao]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database