Search code examples
c++dllembedded-resource

C++: Access embedded resource from dll


I have a c++ dll project, in which, I have embedded some raw data through "resource.rc" file.

IDR_TEMPLATE1           RCDATA                "areaTemplate.bin"

Now I want to access the data of "areaTemplate.bin" file from the dll. How can I read the contents of "areaTemplate.bin" in a byte array?


Solution

  • First use FindResource or FindResourceEx, then use LoadResource and LockResource.

    Use SizeofResource to get the size of datas.

    Code:

    HMODULE g_hModDll;
    
    [...]
    
    HRSRC hRscr = FindResource( g_hModDll, MAKEINTRESOURCE( IDR_TEMPLATE1 ),
                                MAKEINTRESOURCE( RT_RCDATA ) );
    if ( hRscr ) {
        HGLOBAL hgRscr = LoadResource( g_hModDll, hRscr );
        if ( hgRscr ) {
            PVOID pRscr = LockResource( hgRscr );
            DWORD cbRscr = SizeofResource( g_hModDll, hRscr );
        }
    }
    

    Be sure to read the following remark about LoadResource:

    Remarks The return type of LoadResource is HGLOBAL for backward compatibility, not because the function returns a handle to a global memory block. Do not pass this handle to the GlobalLock or GlobalFree function.

    There is no "unlock resource" or "free resource" APIs.

    Remarks The pointer returned by LockResource is valid until the module containing the resource is unloaded. It is not necessary to unlock resources because the system automatically deletes them when the process that created them terminates.