WonFeiHong
WonFeiHong

Reputation: 445

How to use FindResourceW() Properly?

A simple example here I want to load some embedded text file to my application but when I use FindResourceW I get compile-time error:

HGLOBAL     res_handle = NULL;
HRSRC       res;
wchar_t*    res_data;
DWORD       res_size;

// NOTE: providing g_hInstance is important, NULL might not work
res = FindResourceW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(MY_RESOURCE), RT_RCDATA);
if (!res)
    return 1;

In my .rc file I defined the resource like this:

MY_RESOURCE RCDATA    L"Help topics.txt"

The error:

Severity Code Description Project File Line Error C2664 'HRSRC FindResourceW(HMODULE,LPCWSTR,LPCWSTR)': cannot convert argument 3 from 'LPSTR' to 'LPCWSTR' FindFilesProj C:\Users\WongFei\Desktop\FindFilesProj UNICODE\WinMain.cpp 674

Upvotes: 0

Views: 3050

Answers (1)

xMRi
xMRi

Reputation: 15375

You are using RT_RCDATA, which is defined as:

#define RT_RCDATA           MAKEINTRESOURCE(10)

And MAKEINTRESOURCE() is defined as:

#define MAKEINTRESOURCEA(i) ((LPSTR)((ULONG_PTR)((WORD)(i))))
#define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i))))
#ifdef UNICODE
#define MAKEINTRESOURCE  MAKEINTRESOURCEW
#else
#define MAKEINTRESOURCE  MAKEINTRESOURCEA
#endif // !UNICODE

You have a project were UNICODE isn't defined. So MAKEINTRESOURCE() returns a char* but FindeResourceW() wants a wchar_t* instead. Thus the compiler error. You can't use RT_RCDATA as-is in combination with FindResourceW() when UNICODE isn't defined.

Use FindResource() instead of FindResourceW(). This makes sure that MAKEINTRESOURCE() returns a pointer of the same type (UNICODE or non-UNICODE) that FindResource() expects:

res = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(MY_RESOURCE), RT_RCDATA);

Otherwise, you have to type-cast RT_RCDATA to wchar_t* to match what FindResourceW() expects:

 res = FindResourceW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(MY_RESOURCE), (LPWSTR)RT_RCDATA);

The type-cast is safe.

Remember that your resource is stored in the way you created it. There may be need to convert it into the proper character mode you need.

Upvotes: 3

Related Questions