How to get an error message box when LoadLibrary fails?

339 Views Asked by At

I want the proc to show detailed information such as which dependency is missing, whether the dll is invalid...

int main(int argc, char *argv[]) {
    // Record original error mode
    UINT prevErrorMode = GetErrorMode();
    ::SetErrorMode(0);

    std::wstring wstr;

    // Get library absolute path and store into wstr.
    // ...

    typedef int (*EntryFun)(int, char *[]);

    HINSTANCE hDLL = ::LoadLibraryW(wstr.data());
    int res = -1;
    if (hDLL != NULL) {
        EntryFun fun = (EntryFun)::GetProcAddress(hDLL, "main_entry");
        if (fun != NULL) {
            // Restore error mode
            SetErrorMode(prevErrorMode);

            res = fun(argc, argv);
        } else {
            res = ::GetLastError();
            ::MessageBoxW(nullptr, TO_UNICODE("Failed to find entry!"), TO_UNICODE("Error"),
                          MB_OK | MB_ICONERROR);
        }
        ::FreeLibrary(hDLL);
    } else {
        res = ::GetLastError();
        ::MessageBoxW(nullptr, TO_UNICODE("Failed to load main module!"), TO_UNICODE("Error"),
                      MB_OK | MB_ICONERROR);
    }
    return res;
}

I use SetErrorMode but it doesn't seem to work, there's no message box after LoadLibrary returns NULL.

Also, FormatMessage doesn't help because it cannot provide information about which dependency is missing.

1

There are 1 best solutions below

2
YangXiaoPo-MSFT On

LoadLibrary reports error through GetLastError. The advantage of Run-Time Dynamic Linking is Run-time dynamic linking enables the process to continue running even if a DLL is not available. You may write your own loader to walk through the dependencies yourself until you find what is missing as @RemyLebeau said. There is a MemoryModule repository which loads a DLL completely from memory and you can refer to.

But for Load-Time Dynamic Linking, the system simply terminates the process if it cannot find the DLL.
enter image description here