3

Here the same question for C#: load resource as byte array programmaticaly

So I've got a resource (just binary file - user data, dosen't really matter). I need to get a pointer to byte array representing this resource, how to do this ? Resource located in Resource Files of vs2010 (win32 console project). I think i need to use FindResource, LoadResource and LockResource function of winapi.

Community
  • 1
  • 1
Romz
  • 1,437
  • 7
  • 36
  • 63
  • In Visual Studio you can add resource files – Neel Basu May 13 '13 at 17:43
  • 3
    Q: I think i need to use FindResource, LoadResource and LockResource? A: Yup. Exactly: [How to load a custom binary resource in a VC++ static library as part of a dll?](http://stackoverflow.com/questions/9240188/how-to-load-a-custom-binary-resource-in-a-vc-static-library-as-part-of-a-dll) – paulsm4 May 13 '13 at 17:46

2 Answers2

9

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.

rmhartog
  • 2,293
  • 12
  • 19
  • 1
    `GetModuleHandle(NULL); // get the handle to the current module` - That's not what the API returns. It returns a handle to the module that was used to create the process. This fails when the resource is compiled into a DLL (a common scenario, in particular with respect to localization). One solution is outlined under [Accessing the current module’s HINSTANCE from a static library](https://blogs.msdn.microsoft.com/oldnewthing/20041025-00/?p=37483). – IInspectable May 30 '16 at 14:00
1
HRSRC src = FindResource(NULL, MAKEINTRESOURCE(IDR_RCDATA1), RT_RCDATA);
    if (src != NULL) {
        unsigned int myResourceSize = ::SizeofResource(NULL, src);
        HGLOBAL myResourceData = LoadResource(NULL, src);

        if (myResourceData != NULL) {
            void* pMyBinaryData = LockResource(myResourceData);

            std::ofstream f("A:\\TestResource.exe", std::ios::out | std::ios::binary);
            f.write((char*)pMyBinaryData, myResourceSize);
            f.close();

            FreeResource(myResourceData);
        }
    }
Digital Human
  • 1,599
  • 1
  • 16
  • 26