从 DLL 字符串表中获取字符串
Getting string from a DLL string table
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;
}
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取