Reputation: 67
I have trouble understanding what happens to the getlasterror
function in the below code.
My dll
is a valid one and LoadLibrary
and FreeLibrary
do not fail, but GetLastError
returns:
6 (ERROR_INVALID_HANDLE).
The code:
int main()
{
const char* mydll = "mydll.dll";
HINSTANCE hinstLib;
hinstLib = LoadLibraryA(mydll);
if (hinstLib) {
int rez = FreeLibrary(hinstLib);
if (rez) {
printf(" SUCCESS but Geterror:: %d\n", GetLastError());
}
}
return 0;
}
Upvotes: 1
Views: 472
Reputation: 51894
There is nothing in the documentation for FreeLibrary()
indicating (or even suggesting) that the calling thread's error code will be set on a successful call. Thus, your call to GetLastError()
following a non-zero (successful) return from FreeLibrary()
would seem to be returning an 'arbitrary' value.
From the GetLastError()
documentation:
The Return Value section of the documentation for each function that sets the last-error code notes the conditions under which the function sets the last-error code. Most functions that set the thread's last-error code set it when they fail. However, some functions also set the last-error code when they succeed. If the function is not documented to set the last-error code, the value returned by this function is simply the most recent last-error code to have been set; some functions set the last-error code to 0 on success and others do not.
You could probably verify this by explicitly setting your thread's error code before calling FreeLibrary()
:
//...
SetLastError(0); // Set last error code
int rez = FreeLibrary(hinstLib);
//...
EDIT: If, even with this in place, you are still seeing a 'consistent' value for the last error, then it is likely that your mydll.dll
is itself calling a WinAPI function that fails (with the reason/error being INVALID_HANDLE_VALUE
), from code executed in the DLL_PROCESS_DETACH
section of its DllMain()
procedure. However, if that procedure still returns TRUE
, then the FreeLibrary()
function will also return TRUE
(i.e. it will signal that your DLL was unloaded).
Upvotes: 2