1.简介与安装
简介: 无, 懂的都懂
安装
sudo apt install protobuf-compiler protobuf-c-compiler libprotobuf-dev
编译依赖
pkg-config --cflags --libs protobuf
-pthread -lprotobuf -pthread
编译选项: -pthread
链接选项: -lprotobuf -pthread
2.实例
1.代码
实例1
addressbook.proto
syntax = "proto3";
package tutorial;
message Person {
string name = 1;
string email = 2;
}
message AddressBook {
repeated Person people = 1;
}
1_addressbook_protobuf实例.cc
#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
void WriteAddressBook()
{
tutorial::AddressBook address_book;
// 添加一个 Person
tutorial::Person *person = address_book.add_people();
person->set_name("Alice");
person->set_email("[email protected]");
// 写入到文件
std::ofstream output("addressbook.data", std::ios::binary);
if (!address_book.SerializeToOstream(&output))
{
std::cerr << "Failed to write address book." << std::endl;
return;
}
}
void ReadAddressBook()
{
tutorial::AddressBook address_book;
// 从文件读取
std::ifstream input("addressbook.data", std::ios::binary);
if (!address_book.ParseFromIstream(&input))
{
std::cerr << "Failed to read address book." << std::endl;
return;
}
// 输出读取到的人名
for (int i = 0; i < address_book.people_size(); ++i)
{
const tutorial::Person &person = address_book.people(i);
std::cout << "Name: " << person.name() << ", Email: " << person.email() << std::endl;
}
}
int main()
{
WriteAddressBook();
ReadAddressBook();
return 0;
}
实例2
person.proto
syntax = "proto3"; // 使用Protocol Buffe