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

Preferred way of extracting and matching protobuf message typename from an Any package

本文关键字:类型 方法 消息 protobuf 包中 Any 提取      更新时间:2023-10-16

我一直在使用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...

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

相关文章: