【问题标题】:How to get a list of methods from a particular gRPC service in C++?如何从 C++ 中的特定 gRPC 服务获取方法列表?
【发布时间】:2021-09-28 21:41:44
【问题描述】:

我有一个使用这些方法的 proto3 gRPC 服务:

syntax = "proto3";

Service MyService
{
    rpc Foo (FooRequest) returns (FooResponse) {}
    rpc Bar (BarRequest) returns (BarResponse) {}
   // etc.
}    

我想在我的 C++ 应用程序中动态访问这些方法,例如

google::protobuf::ServiceDescriptor serviceDescriptor;
google::protobuf::MethodDescriptor* myMethod = serviceDescriptor.FindMethodByName("Foo");

使用google::protobuf::MessageDescriptor = myMessage.GetDescriptor(); 获取消息描述符很简单,但似乎没有对服务等效的方法。

如何为 C++ 中的服务获取 ServiceDescriptor

我的直觉是,获取 gRPC 方法列表需要获取 ServiceDescriptor,但如果有其他方法可以实现这一点,我也会感兴趣。

【问题讨论】:

标签: c++ protocol-buffers grpc proto3 grpc-c++


【解决方案1】:

如果您静态链接 Protobuf 生成的源文件(例如 MyService.pb.cc),您应该能够从 generated_poolDescriptorPool 获取 ServiceDescriptor。

#include <google/protobuf/descriptor.h>
int main(int argc, char** argv)
{
  const google::protobuf::DescriptorPool* p = google::protobuf::DescriptorPool::generated_pool();
  const google::protobuf::ServiceDescriptor* serviceDescriptor = p->FindServiceByName("MyService");
  const google::protobuf::MethodDescriptor* method = serviceDescriptor->FindMethodByName("Foo");
}

另见Protobuf message object creation by name

要获取服务方法的完整列表,您可以使用int ServiceDescriptor::method_count() constconst MethodDescriptor* ServiceDescriptor::method(int index) const

【讨论】:

    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多