麻烦大家去官网先下载
Download Protocol Buffers | Google Developers 从官网跳到github
Release Protocol Buffers v3.18.0 · protocolbuffers/protobuf · GitHub
下载
tar -xvf protobuf-cpp-3.18.0.tar.gz
cd protobuf-3.18.0/
./configure -prefix=/usr/local/
make
make install
protoc --version
bytes 和 string 区别
- protobuf里的
string/bytes
在C++接口里实现上都是std::string
。 - 两者序列化、反序列化格式上一致,不过对于
string
格式,会有一个utf-8格式的检查。
出于效率,我们应当在确定字段编码格式后直接使用bytes
,减少utf8编码的判断,效率上会有提高。
#include <iostream>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/io/coded_stream.h>
using namespace google::protobuf;
using namespace google::protobuf::compiler;
int main() {
// 初始化 Protocol Buffers 库
GOOGLE_PROTOBUF_VERIFY_VERSION;
// 创建一个Importer对象来处理.proto文件
Importer importer("", nullptr);
// 加载指定的proto文件
const std::string filename = "person.proto";
const FileDescriptor* fileDesc = importer.pool()->FindFileByName(filename);
if (fileDesc != nullptr) {
std::cout << "成功找到文件: " << filename << std::endl;
// 获取文件的所有消息类型
for (int i = 0; i < fileDesc->message_type_count(); i++) {
const Descriptor* messageType = fileDesc->message_type(i);
std::cout << "消息类型: " << messageType->name() << std::endl;
}
} else {
std::cerr << "未能找到文件: " << filename << std::endl;
}
// 清理资源
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
方法二直接immport:
#include <iostream>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/io/coded_stream.h>
using namespace google::protobuf;
using namespace google::protobuf::compiler;
int main() {
// 初始化 Protocol Buffers 库
GOOGLE_PROTOBUF_VERIFY_VERSION;
// 创建 Importer 对象来处理 .proto 文件
Importer importer("", nullptr);
// 导入 msg.proto 文件
const std::string filename = "msg.proto";
const FileDescriptor* fileDesc = importer.Import(filename);
if (fileDesc != nullptr) {
std::cout << "成功找到文件: " << filename << std::endl;
// 获取文件中的所有消息类型
for (int i = 0; i < fileDesc->message_type_count(); i++) {
const Descriptor* messageType = fileDesc->message_type(i);
std::cout << "消息类型: " << messageType->name() << std::endl;
}
} else {
std::cerr << "未能找到文件: " << filename << std::endl;
}
// 清理资源
google::protobuf::ShutdownProtobufLibrary();
return 0;
}