【问题标题】:Glib::Regex returns junk, but equivalent C functions work fineGlib::Regex 返回垃圾,但等效的 C 函数工作正常
【发布时间】:2021-07-09 10:40:21
【问题描述】:

我正在尝试使用 Glib::Regex,但它总是返回垃圾。

下面是简化版的代码:

void testGetPos(std::string fileName){
    auto regEx = Glib::Regex::create(
        "^sprite_[0-9]+__x(-?[0-9]+)_y(-?[0-9]+)\\.tif$",
        Glib::REGEX_CASELESS
    )

    Glib::MatchInfo match;

    if(!regEx->match(fileName, match)){
        continue;
    }

    if(!match.matches()){
        continue;
    }

    auto posX = match.fetch(1);
    auto posY = match.fetch(2);

    // ... Use posX and posY
}

int main(){
    testGetPos("sprite_000__x-28_y-32.tif");
}

运行后,posX 和 posY 被垃圾填充。但是,在包装对象上使用 C 函数:

void testGetPos(std::string fileName){
    auto regEx = Glib::Regex::create(
        "^sprite_[0-9]+__x(-?[0-9]+)_y(-?[0-9]+)\\.tif$",
        Glib::REGEX_CASELESS
    )

    GMatchInfo *match = nullptr;
    if(!g_regex_match(regEx->gobj(), fileName.c_str(), (GRegexMatchFlags)0, &match)){
        if(match != nullptr){
            g_match_info_free(match);
        }
        return;
    }

    auto posX = g_match_info_fetch(match, 1);
    auto posY = g_match_info_fetch(match, 2);

    // ... Use posX and posY

    g_free(posX);
    g_free(posY);
    g_match_info_free(match);
}

int main(){
    testGetPos("sprite_000__x-28_y-32.tif");
}

工作正常。是我做错了什么还是坏了。

【问题讨论】:

    标签: c++ gtkmm glibmm


    【解决方案1】:

    所以,在写完这个问题之后,我又尝试了一件事情并解决了它。我想我最好在这里记录一下,以防其他人遇到同样的问题。

    我改了等价的:

    void testGetPos(std::string fileName){
    

    到这样的事情:

    void testGetPos(std::string _fileName){
        Glib::ustring fileName = Glib::filename_to_utf8(_fileName);
    

    TL;DR:正在将隐式创建的临时对象传递给 regEx->match,而 Glib::MatchInfo 需要访问 Glib::ustring 引用。

    原来问题是这样的:regEx->match(fileName, match)const Glib::ustring & 作为它的第一个参数,但我传递给它的是const std::string &,它正在被隐式转换。在大多数情况下,这很好,但是,Glib::MatchInfo 引擎盖下的 GMatchInfo 对象 不会 复制传递给 match 函数的字符串,它需要 strong> 该数据在对象被释放之前可用。当我使用std::string 参数调用regEx->match 时,会在regEx->match 执行时创建一个临时Glib::ustring 对象,并在它完成后销毁。这意味着Glib::MatchInfo 正在访问的数据现在无效,因此返回垃圾。通过使用Glib::filename_to_utf8,我创建了一个生命周期超过使用它的Glib::MatchInfo 对象的变量,并使用和适当的转换函数。

    希望这对遇到此问题的其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-23
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2012-12-10
      相关资源
      最近更新 更多