-1

I have a dynamic library which uses LoadImage function:

HINSTANCE hInstance = (HINSTANCE)(LONG_PTR)GetWindowLongPtr(wnd, GWLP_HINSTANCE);
HBITMAP hBitMap = (HBITMAP) LoadImage(hInstance, MAKEINTRESOURCE(resId), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

That library is linked to the main application (exe). When the application calls a library function which calls LoadImage I get Win api error 1813. hInstance refers to the exe file. How to fix that ?

Irbis
  • 1,432
  • 1
  • 13
  • 39
  • 2
    The error text is `"The specified resource type cannot be found in the image file."`. Maybe your `resId` is invalid. – wohlstad Jan 30 '23 at 11:27
  • @wohlstad resId is correct. – Irbis Jan 30 '23 at 11:30
  • 2
    `GetWindowLongPtr(wnd, GWLP_HINSTANCE)` is wrong. you must take `hInstance` from `&__ImageBase` if it in your dll, or from LoadLibraryW/GetModuleHandleW if it in another dll/exe – RbMm Jan 30 '23 at 12:09
  • Think that problem lies you want load image from dll but instead your code trying to load resource from exe. – Jozo121 Jan 30 '23 at 11:30
  • In other words, it is using the wrong `HINSTANCE` to load from. – Remy Lebeau Jan 30 '23 at 16:05

1 Answers1

1

LoadImage works when I get HINSTANCE this way:

HMODULE GetModule()
{ 
    HMODULE hMod = NULL;
    GetModuleHandleEx(
        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
        (LPCTSTR)GetModule,
        &hMod);

    return hMod;
}

HINSTANCE hInstance = (HINSTANCE)GetModule();

Please review my answer.

Irbis
  • 1,432
  • 1
  • 13
  • 39
  • `hInstance = (HINSTANCE)&__ImageBase` – RbMm Jan 30 '23 at 22:25
  • Where ```__ImageBase``` is defined ? Which header should I include ? – Irbis Jan 31 '23 at 08:48
  • https://stackoverflow.com/a/557859/6401656 if you search - you found alot of links. And if you search in header files - you found where it defined – RbMm Jan 31 '23 at 09:37
  • How it differ from my answer ? – Irbis Jan 31 '23 at 11:24
  • `(HINSTANCE)&__ImageBase` this is simply use constant. you use 2 api calls, which not need – RbMm Jan 31 '23 at 11:42
  • 1
    `__ImageBase` is a pseudo linker variable that gets dropped into the .obj with an RVA of 0 by the linker. The net result is that determining the `HMODULE` of the module that contains the currently executing code is just a memory lookup. No function calls, and no error handling required. It is supported by MS' link.exe, lld (Clang), and ld (GCC). – IInspectable Jan 31 '23 at 15:16