I get jargons while converting HTML resource to CString in an MFC application. Any help will be appreciated. I am compiling on VC 2022, obviously with unicode.
CString GetHTML(const int& RESOURCE_ID)
{
CString str;
HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(RESOURCE_ID), RT_HTML);
if (hrsrc != NULL)
{
HGLOBAL pResource = LoadResource(NULL, hrsrc);
if (pResource != NULL)
{
LPCTSTR lpctstr = static_cast<LPCTSTR>(LockResource(pResource));
if (lpctstr != NULL)
{
str = CString(lpctstr, ::SizeofResource(NULL, hrsrc));
return str;
}
UnlockResource(pResource);
}
FreeResource(pResource);
}
return NULL;
}
CodePudding user response:
My psychic powers suggest that the your HTML resource file is ascii, but you are casting the ascii bytes returned by LockResource to be a unicode string LPCTSTR (pointer to TCHAR).
Simplest approach would be to have your function return a CStringA
instead of a CStringW
and do all your processing on the string as ascii.
Declare your function to return a CStringA
instance explicitly:
CStringA GetHTML(const int& RESOURCE_ID)
{
CStringA str;
Then, instead of this:
LPCTSTR lpctstr = static_cast<LPCTSTR>(LockResource(pResource));
if (lpctstr != NULL)
{
str = CString(lpctstr, ::SizeofResource(NULL, hrsrc));
return str;
}
This:
const char* psz = static_cast<const char*>(LockResource(pResource));
if (psz != NULL)
{
str = CStringA(psz);
return str;
}
Alternatively, if you want to return a unicode CString(W) from your function, you could convert the resource to unicode using MultiByteToWideChar
API. MFC/ATL provides a convenient macro for doing this.
const char* psz = static_cast<const char*>(LockResource(pResource));
if (psz != NULL)
{
USES_CONVERSION;
CStringW strW = A2W(psz);
return strW;
}
Also, notice that I removed all LPCTSTR references. I have numerous rants about avoiding TCHAR macros.