做个测试,用VC6生成个Win32的DLL,DLL中只有个DllMain。然后用LoadLibrary加载该DLL。之后用GetLastError查看错误信息,返回说“无效句柄”,但返回的句柄并不为NULL,看看MSDN 说明:
If the function succeeds, the return value is a handle to the module.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
如果LoadLibrary失败,返回值为NULL;也就是说若返回值不为NULL,那LoadLibrary就调用成功了。但为什么GetLastError返回“无效句柄”,不成功呢 ?再看MSDN:
The return value is the calling thread's last-error code.
GetLastError得到的只是调用线程的最后错误码;
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.
大多数的函数当执行失败时会设置线程的最后错误码(使用SetLastError),有些函数执行成功也设置线程的最后错误码(调用SetLastError)。而LoadLibrary如同大多数函数一样,失败时(handle为NULL时)才设置错误码,所以若handle不为NULL,则说明函数调用成功,那么用GetLastError 得到的就肯定不是LoadLibrary的错误信息。你会发现用该句柄,可以成功GetProcAddress,说明该句柄是确实有效的。
You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data. That is because some functions call SetLastError with a zero when they succeed, wiping out the error code set by the most recently failed function.