Load resource as byte array programmaticaly in C++

后端 未结 2 1622
渐次进展
渐次进展 2020-12-03 13:06

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

相关标签:
2条回答
  • 2020-12-03 13:36
    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);
            }
        }
    
    0 讨论(0)
  • 2020-12-03 13:41

    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.

    0 讨论(0)
提交回复
热议问题