在 C++ 代码中调用 Protocol Buffers 编译器 protoc 的库进行 .proto 文件的解析并生成代码,可以使用 Protocol Buffers 的动态库 libprotoc 提供的 API。以下是一个简单的步骤:包含必要的头文件:
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/compiler/parser.h>
#include <google/protobuf/compiler/code_generator.h>
初始化 Protobuf 动态库
GOOGLE_PROTOBUF_VERIFY_VERSION;
创建 Importer 和 Parser 实例:
google::protobuf::compiler::DiskSourceTree sourceTree;
google::protobuf::compiler::Importer importer(&sourceTree, nullptr);
google::protobuf::compiler::Parser parser;
添加 .proto 文件的路径
sourceTree.MapPath(“”, “/path/to/your/proto/files”);
从 Importer 加载 .proto 文件
const google::protobuf::FileDescriptor* file = importer.Import(“your_proto_file.proto”);
生成代码
google::protobuf::compiler::CodeGeneratorRequest request;
google::protobuf::compiler::CodeGeneratorResponse response;
// 设置 CodeGeneratorRequest 的内容
request.set_file_to_generate(0, file->name());
// 调用 CodeGenerator 生成代码
google::protobuf::compiler::GeneratorContext generatorContext;
generatorContext.SetParameter(“cpp_out”, “/path/to/output/directory”);
google::protobuf::compiler::cpp::CppGenerator cppGenerator;
cppGenerator.Generate(file, generatorContext, &request, &response);
保存生成的代码
for (const auto& file : response.file()) {
// file.name() 是生成代码的文件名
// file.content() 是生成的代码内容
// 可以将内容保存到相应的文件中
}
清理
google::protobuf::ShutdownProtobufLibrary();