从 DLL 字符串表中获取字符串

Getting string from a DLL string table

本文关键字:字符串 获取 DLL      更新时间:2023-10-16
HMODULE m_LangDll;  
wchar_t* GetString(const int StringID)
{
    wchar_t* nn = {0};
    if (m_LangDll)
    {
        wchar_t temp[2048];
        if(::LoadString(m_LangDll, StringID, temp, 2048))
        {
            MessageBox(0, L"string found", 0, 0);
            nn = temp;
            return nn;
        }
    }
    //assert(s.length() && _T("String not found!"));
    return 0;
}

这段代码工作得很好。它返回我想要的字符串没有问题。

如果我删除消息框(0,L"找不到字符串",0,0),它不会。它返回一个随机字符。我显然做错了什么。我只是不明白对 MessageBox(0,0,0,0) 的看似无关的调用有什么影响。

我尝试用其他代码替换消息框调用。就像分配更多wchar_t*一样,但这似乎与调用 MessageBox 有关。

我一直在称呼GetString,就像...

MessageBox(0, GetString(101),L"HHHHH", 0);

当我称它为这样时,我会得到一堆不同的胡言乱语......

wchar_t* tempString = GetString(101);
MessageBox(0, tempString, 0, 0);

但这两种方式都可以工作,只要我不在 GetString 中注释掉 MessageBox()

[编辑]

感谢您的回复,他们都非常有帮助。

我的代码现在是

wchar_t* GetString(const int StringID)
{
    wchar_t* nn = new wchar_t[2048];
    if (m_LangDll)
    {
        if(::LoadString(m_LangDll, StringID, nn, 2048))
        {       
        return nn;
        }
    }
    delete [] nn;
    //assert(s.length() && _T("String not found!"));
    return 0;
}

特别感谢尼戈加布。

再问一个问题。为什么 MessageBox() 会让代码工作?

您正在从函数返回局部变量的地址,从而导致未定义的行为:

nn = temp; // when the function returns temp is out of scope
return nn; // and n is pointing at temp.

改为返回std::wstring并使用c_str()访问const wchar_t*表示形式。

也许,问题是 GetString() 返回一个指向堆栈上分配的缓冲区的指针('temp' 局部变量)。从技术上讲,缓冲区在返回

HMODULE m_LangDll; wchar_t* GetString(const int StringID) { wchar_t* nn = new wchar_t[2048]; if (m_LangDll) { if(::LoadString(m_LangDll, StringID, nn, 2048)) { MessageBox(0, L"string found", 0, 0); nn = temp; return nn; } } delete [] nn; //assert(s.length() && _T("String not found!")); return 0; }