首页 > 解决方案 > 从 Any 包中提取和匹配 protobuf 消息类型名的首选方式

问题描述

我一直在使用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 的“基本名称”。

谢谢!

标签: c++protocol-bufferspackaging

解决方案


你可以试试

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


推荐阅读