【发布时间】:2016-12-21 07:50:17
【问题描述】:
我是 C++ 新手,需要一些帮助。 我创建了一个包含字符串的纯资源 dll,我需要在不同的项目中使用这个 dll 来读取存储的字符串。
我编写了以下函数来读取字符串:
LPTSTR GetResourceStr(HMODULE resContainer,int resourceID)
{
//The stings that are stored in the dll are:
//
//ID |Value|Caption
//__________________________________________
//IDS_STRING101 |101 |stringggg
//IDS_STRING102 |102 |string 102
//IDS_STRING103 |103 |string 103
LPTSTR strBuffer = NULL;//is a (non-const) TCHAR string
if(0!=resContainer){
int copied=LoadString(resContainer,resourceID ,(LPTSTR)&strBuffer,0);
}
return strBuffer;
}
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE resContainer=LoadLibraryEx(L"ResourceDll.dll",NULL, LOAD_LIBRARY_AS_DATAFILE);
LPTSTR msg = GetResourceStr(resContainer,101);
std::wcout<<msg<<std::endl;
//Expected output: stringggg
//The output that i get: stringgggstring 102 string 103
int i = 0;
std::cin>>i;
return 0;
}
为了获得预期的输出 - stringggg,我应该在我的代码中进行哪些更改? 为什么会这样? LoadString 是否为它从资源中读取的字符串分配了内存,或者我只是获得了指向该字符串已经存储在内存中的位置的指针? 谢谢你的帮助!!
【问题讨论】:
-
您需要一个 LPTSTR[] 以便它可以将字符串复制到您的缓冲区中。最后一个参数必须是该数组的大小,0 永远不正确。返回该数组将是一个悬空指针错误。考虑返回一个 std::wstring。
标签: c++ resources stringreader resourcestring