代码之家  ›  专栏  ›  技术社区  ›  kakyo

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

  •  0
  • kakyo  · 技术社区  · 5 年前

    我一直在用 Any 为protobuf打包动态消息。 在接收器端,我用 Any.type_url() 以匹配所附的消息类型。

    如果我错了就纠正我 .GetDescriptor() 无法与 任何 ,我仍然想使匹配减少混乱。我试着用这样的暴力来提取消息类型:

    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类型的“basename”。

    谢谢!

    0 回复  |  直到 5 年前
        1
  •  1
  •   Stf Kolev    5 年前

    你可以试试

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

    如果它很适合你。

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

    假设有两个param作为basename: http://url.com/example/2

    这是最新的,是2。。。

    如果你不寻求跨平台的支持,你总是可以 https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/splitpath-wsplitpath?view=vs-2019