gpt4 book ai didi

protocol-buffers - 从使用 protoc 生成的 pb2.py 逆向工程 .proto 文件

转载 作者:行者123 更新时间:2023-12-05 01:54:53 33 4
gpt4 key购买 nike

是否可以使用 protoc 从生成的 pb2.py 中获取 proto 文件? gRPC 是否可以进行相同的逆向工程?

最佳答案

_pb2.py 文件的格式因 protobuf-python 版本而异,但大多数版本内部都有一个名为 serialized_pb 的字段。这包含 FileDescriptorProto.proto 文件的整个结构格式:

serialized_pb=b'\n\x0c...'

这可以传递给 protoc 编译器来为其他语言生成 header 。但是,必须先将其放入 FileDescriptorSet 中才能正确匹配格式。这可以使用 Python 完成:

import google.protobuf.descriptor_pb2
fds = google.protobuf.descriptor_pb2.FileDescriptorSet()
fds.file.append(google.protobuf.descriptor_pb2.FileDescriptorProto())
fds.file[0].ParseFromString(b'\n\x0c... serialized_pb data ....')
open('myproto.txt', 'w').write(str(fds))
open('myproto.pb', 'wb').write(fds.SerializeToString())

上面的代码片段将人类可读的版本保存到 myproto.txt 并将名义上与 protoc 兼容的格式保存到 myproto.pb .文本表示如下所示:

file {
name: "XYZ.proto"
dependency: "dependencyXYZ.proto"
message_type {
name: "MyMessage"
field {
name: "myfield"
number: 1
label: LABEL_OPTIONAL
type: TYPE_INT32
}
...

例如,现在可以使用以下方法生成 C++ header :

protoc --cpp_out=. --descriptor_set_in=myproto.pb XYZ.proto

请注意,XYZ.proto 必须与描述符集中的文件名相匹配,您可以在 myproto.txt 中查看。然而,如果文件有依赖关系,这种方法很快就会变得困难,因为所有这些依赖关系都必须收集在同一个描述符集中。在某些情况下,仅使用文本表示手动重写 .proto 文件可能更容易。

关于protocol-buffers - 从使用 protoc 生成的 pb2.py 逆向工程 .proto 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70479912/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com