Load resource as byte array programmaticaly in C++

To obtain the byte information of the resource, the first step is to obtain a handle to the resource using FindResource or FindResourceEx. Then, load the resource using
LoadResource. Finally, use LockResource to get the address of the data and access SizeofResource bytes from that point. The following example illustrates the process:

HMODULE hModule = GetModuleHandle(NULL); // get the handle to the current module (the executable file)
HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(RESOURCE_ID), RESOURCE_TYPE); // substitute RESOURCE_ID and RESOURCE_TYPE.
HGLOBAL hMemory = LoadResource(hModule, hResource);
DWORD dwSize = SizeofResource(hModule, hResource);
LPVOID lpAddress = LockResource(hMemory);

char *bytes = new char[dwSize];
memcpy(bytes, lpAddress, dwSize);

Error handling is of course omitted for brevity, you should check the return value of each call.

Leave a Comment