protocol-buffers - 如何从 protobuf 描述符获取方法选项?

标签 protocol-buffers protoc

我尝试使用 protobuf 编译器解析 .proto 文件。但这里有一个令人困惑的问题,我无法获得方法的选项。

似乎我的选项被视为“未知字段”,但选项不是。

有什么办法可以解决这个问题吗?谢谢。

(我不想在这里粘贴大量代码,但我认为完整描述问题非常重要。对此感到抱歉。)

(环境:g++ 4.7、Ubuntu 16.04、Protobuf 3.0.0)

#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/compiler/importer.h>

using namespace std;
using namespace google::protobuf;
using namespace google::protobuf::compiler;

#define print(x) std::cout << x << std::endl
#define input(x) std::cin >> x

int main() {
    DiskSourceTree sourceTree;
    sourceTree.MapPath("", "./");
    sourceTree.MapPath("", "./protobuf/include/");
    Importer importer(&sourceTree, NULL);

    auto fd = importer.Import("example.proto");
    assert(fd);

    int service_count = fd->service_count();

    for (int i = 0; i < service_count; i++) {
        auto service_d = fd->service(i);
        int method_count = service_d->method_count();
        for (int j = 0; j < method_count; j++) {
            auto method_d = service_d->method(j);
            print(method_d->options().unknown_fields().field_count());$ 
            print(">> " << method_d->options().uninterpreted_option_size());
        }
    }
    return 0;
}

// lrpc.proto
syntax = "proto3";
package lrpc;
import "google/protobuf/descriptor.proto";


extend google.protobuf.MethodOptions {
    int32 CmdID      = 50000;
    string OptString = 50001;
    string Usage     = 50002;
}

// example.proto
syntax = "proto3";

package foobar;

import "google/protobuf/wrappers.proto";
import "google/protobuf/empty.proto";

import "lrpc.proto";

message SearchRequest {
    // ... 
}

message SearchResponse {
    // ...
}

service SearchService {
    rpc Search( SearchRequest ) returns( SearchResponse ) {
        option( lrpc.CmdID ) = 1;
    }
}

最佳答案

这些选项不是未知字段,因为它们是 extensions !据称,proto3 中的扩展已被删除,但是当您使用 Importer 动态解析 .proto 文件时,无论您声明的语法版本如何,都会启用扩展。

如果您向内部 for() 循环添加一行,例如:

print(method_d->options().DebugString());

您将得到如下输出:

[lrpc.CmdID]: 1

您可以使用 protobuf 反射枚举扩展值——它们会在您调用 Reflection::ListFields() 时显示.

关于protocol-buffers - 如何从 protobuf 描述符获取方法选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165197/

相关文章:

java - protobuf生成代码导致的Eclipse构建循环(与Maven Project Builder相关)

go - 如何使用带有版本化 Go 模块的 fork 模块(v1.11+,GO111MODULE=on)

objective-c - Protobuf 与二进制 plist 在 iOS 游戏中的网络交易

go - 使用protoc生成golang代码时导入和使用其他.proto文件出错

java - eclipse中hadoop中的protoc错误

java - Hadoop 3.1构建在 `protoc --version`失败

java - Gradle 禁用所有增量编译和并行构建

python - 为什么我的 Protobuf 消息(在 Python 中)忽略了零值?

protocol-buffers - 导入另一个 proto 文件时出错

go - 错误 : failed post-processing: 820:39: missing ',' in argument list