0
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;
}

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

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

我尝试用其他代码替换 MessageBox 调用。就像分配更多 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;
}

特别感谢 neagoegab。

还有一个问题。为什么 MessageBox() 会使代码工作?

4

3 回答 3

0

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

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

std::wstring而是返回 a并用于c_str()访问const wchar_t*表示。

于 2012-12-13T14:50:31.360 回答
0

您的临时变量在堆栈上...在堆上分配它:

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;
}
于 2012-12-13T14:53:21.443 回答
0

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

于 2012-12-13T14:54:07.430 回答