【问题标题】:Preferred way of extracting and matching protobuf message typename from an Any package从 Any 包中提取和匹配 protobuf 消息类型名的首选方式
【发布时间】:2019-11-29 08:34:31
【问题描述】:

我一直在使用Any 为 protobuf 打包动态消息。 在接收端,我使用Any.type_url() 来匹配封闭的消息类型。

如果我错了,请纠正我,知道.GetDescriptor() 不能与Any 一起使用,我仍然想让匹配不那么混乱。我试图用这样的蛮力提取消息类型:

MyAny pouch;

// unpacking pouch
// Assume the message is "type.googleapis.com/MyTypeName"
....


const char* msgPrefix = "type.googleapis.com/";
auto lenPrefix = strlen(msgPrefix);
const std::string& msgURL = pouch.msg().type_url();
MamStr msgName = msgURL.substr(lenPrefix, msgURL.size());

if (msgName == "MyTypeName") {

   // do stuff ...

}

但我仍然想知道是否有更简洁的方法可以跳过前缀以获取类型 URL 的“基本名称”。

谢谢!

【问题讨论】:

  • 如果适合你,你可以试试std::string getBaseName(std::string const & url) { return url.substr(url.find_last_of("/\\") + 1); }。虽然有一些情况,但它可能无法正确爆炸。假设您有两个参数作为基本名称:http://url.com/example/2 这将获得最新的,即 2... 如果您不是在寻找跨平台支持,您可以随时选择 docs.microsoft.com/en-us/cpp/c-runtime-library/reference/…

标签: c++ protocol-buffers packaging


【解决方案1】:

你可以试试

std::string getBaseName(std::string const & url) { 
    return url.substr(url.find_last_of("/\\") + 1); 
}

如果它适合你。

虽然有一些情况,但它可能不会正确爆炸。

假设您有两个参数作为基本名称:http://url.com/example/2

这会得到最新的,也就是2...

如果您不是在寻找跨平台支持,您可以随时选择https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/splitpath-wsplitpath?view=vs-2019

【讨论】:

  • 好的。我认为 protobuf 中可能有一个魔术助手 API,但如果这是我们能做的最好的,那么我会接受这个答案。谢谢。
  • 不幸的是,当我查看文档时,我没有发现任何辅助方法/属性或任何可以解析比type_url() 更远的东西。这就是我将其发布为答案的原因。
猜你喜欢
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 2020-11-23
  • 2015-12-03
  • 2018-04-12
  • 2013-05-21
  • 2020-03-07
  • 1970-01-01
相关资源
最近更新 更多