从描述符字符串恢复 .proto 文件。可能的?

OGP*_*OGP 3 protocol-buffers

是否可以将包含 Protocol Buffers 描述符的字符串反编译回 .proto 文件?

假设我有一个长字符串,例如

\n\file.proto\u001a\u000ccommon.proto\"\u00a3\u0001\n\nMsg1Request\u0012\u0017\n\u0006common\u0018\u0001 ...ETC。

我需要恢复 .proto,不需要完全按照原来的样子,但可以编译。

Ken*_*rda 6

在 C++ 中,FileDescriptor接口有一个方法DebugString()可以按照语法格式化描述符内容.proto——即正是您想要的。为了使用它,您首先需要使用接口编写代码将 raw 转换FileDescriptorProto为 a 。FileDescriptorDescriptorPool

像这样的事情应该这样做:

#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <iostream>

int main() {
  google::protobuf::FileDescriptorProto fileProto;
  fileProto.ParseFromFileDescriptor(0);
  google::protobuf::DescriptorPool pool;
  const google::protobuf::FileDescriptor* desc =
      pool.BuildFile(fileProto);
  std::cout << desc->DebugString() << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

您需要向该程序提供 FileDescriptorProto 的原始字节,您可以通过使用 Java 使用 ISO-8859-1 字符集将字符串编码为字节来获得该原始字节。

另请注意,如果文件导入任何其他文件,则上述内容不起作用 - 您必须将这些导入加载到DescriptorPool第一个文件中。

  • 公平地说,当我发布这篇文章时,proto3 还不存在。 (2认同)