从Any包中提取和匹配protobuf消息类型名称的首选方法

问题描述 投票:0回答:1

我一直在使用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-buffers packaging
1个回答
0
投票

您可以尝试

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

© www.soinside.com 2019 - 2024. All rights reserved.