关于“LoadLibrary 无效句柄”

做个测试,用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:

GetLastError: 

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.

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值