Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loadlibrary fails for current path with GetLastError() == 0

I have a simple program that loads a DLL from the current path

#include <iostream>
#include <windows.h>

using namespace std;

auto loaddll(const char * library) {
    auto dllModule = LoadLibrary(library);
    if(dllModule == NULL)
        throw "Can't load dll";     
    return dllModule;
}

int main() {
    try {   
        auto Handle = loaddll("ISab.dll");
    } catch(const char * error) {
        cerr << "An Unexpected error :" << error << endl;   
        cerr << "Get Last Error : " << GetLastError();
    }
}

the load library fails for every DLL in the current path but succeeds for DLL like User.dll

if I ran it output will be like

An Unexpected error :Can't load dll
Get Last Error : 0

this also fails if i specify full path to dll

like image 999
jaganantharjun Avatar asked Dec 08 '25 18:12

jaganantharjun


1 Answers

When a Win32 API call fails, and sets the error code, you must call GetLastError before calling any other Win32 API function. You don't do that.

Raising an exception, streaming to cerr etc. are all liable to call other Win32 API functions and so reset the error code.

Your code must look like this:

auto dllModule = LoadLibrary(library);
if (dllModule == NULL)
    auto err = GetLastError();

Once you have the error code you should be better placed to understand why the module could not be loaded. Common error codes for LoadLibrary include:

  • ERROR_MOD_NOT_FOUND which means that the module, or one of its dependencies, cannot be located by the DLL search.
  • ERROR_BAD_EXE_FORMAT which invariably means a 32/64 bit mismatch, either with the module you load, or one of its dependencies.
like image 100
David Heffernan Avatar answered Dec 10 '25 10:12

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!