C ++: access to embedded resource from dll

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

IDR_TEMPLATE1           RCDATA                "areaTemplate.bin"

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

+4
source share
3 answers

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

Use SizeofResource to get the size of the data.

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

LoadResource:

LoadResource - HGLOBAL , , . GlobalLock GlobalFree .

API- " " " ".

, LockResource, , , . , , , , .

+1

Manuell, FindResource(), LoadResource() , , LockResource() SizeofResource()

, , API.

void WriteResourceToFile(
   HANDLE hFile,
   const _tstring &resourceName,
   const _tstring &resourceType,
   HMODULE hModule)
{
   HRSRC hResource = ::FindResource(
      hModule,
      resourceName.c_str(),
      resourceType.c_str());

   if (!hResource)
   {
      const DWORD lastError = ::GetLastError();

      throw CWin32Exception(
         _T("WriteResourceToFile() - FindResource"),
         lastError);
   }

   HGLOBAL hGlobal = ::LoadResource(hModule, hResource);

   if (!hGlobal)
   {
      const DWORD lastError = ::GetLastError();

      throw CWin32Exception(
         _T("WriteResourceToFile() - LoadResource"),
         lastError);
   }

   void *pData = ::LockResource(hGlobal);

   if (!pData)
   {
      const DWORD lastError = ::GetLastError();

      throw CWin32Exception(
         _T("WriteResourceToFile() - LockResource"),
         lastError);
   }

   const DWORD bytes = ::SizeofResource(hModule, hResource);

   DWORD bytesWritten = 0;

   if (!::WriteFile(hFile, pData, bytes, &bytesWritten, 0))
   {
      const DWORD lastError = ::GetLastError();

      throw CWin32Exception(
         _T("WriteResourceToFile() - WriteFile"),
         lastError);
   }

   if (bytesWritten != bytes)
   {
      throw CWin32Exception(
         _T("WriteResourceToFile() - WriteFile"),
         _T("Wrote less bytes (") + ToString(bytesWritten) +
         _T("( than expected: ") + ToString(bytes));
   }
}
+3
// Determine the module handle of your DLL by locating a function
// you know resides in that DLL
HMODULE hModule;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
        (LPCSTR)&myDLLfuncName, &hModule)

HRSRC hRscr = FindResource(hModule, MAKEINTRESOURCE(IDR_TEMPLATE1),
                           MAKEINTRESOURCE(RT_RCDATA));
0
source

All Articles