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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.