简体   繁体   English

LoadLibrary返回Null

[英]LoadLibrary returning Null

I just tried the following code(windows xp sp3, vs2010) and LoadLibrary seems to be returning Null. 我刚刚尝试了以下代码(windows xp sp3,vs2010),LoadLibrary似乎正在返回Null。

#include "windows.h"
#include "stdio.h"

int main() {
    HMODULE hNtdll;
    hNtdll = LoadLibrary(LPCWSTR("ntdll.dll"));
    printf("%08x\n", hNtdll);
}

The output I get is 00000000 . 我得到的输出是00000000 According to the docs , NULL is returned when the function fails. 根据文档 ,函数失败时返回NULL。 I tried using GetLastError and the error code is 126( 0x7e, Error Mod Not Found ). 我尝试使用GetLastError ,错误代码为126( 0x7e,找不到错误模式 )。

How can I correct this issue? 我该如何纠正这个问题?

Thanks! 谢谢!

You have a string literal, which consists of narrow characters. 你有一个字符串文字,由窄字符组成。 Your LoadLibrary call apparently expects wide characters. 您的LoadLibrary调用显然需要宽字符。 Type-casting isn't the way to convert from one to the other. 类型转换不是从一个转换为另一个的方式。 Use the L prefix to get a wide string literal: 使用L前缀获取宽字符串文字:

LoadLibrary(L"ntdll.dll")

Type-casting tells the compiler that your char const* is really a wchar_t const* , which isn't true. 类型转换告诉编译器你的char const*实际上是一个wchar_t const* ,这不是真的。 The compiler trusts you and passes the pointer along to LoadLibrary anyway, but when interpreted as a wide string, the thing you passed is nonsense. 无论如何,编译器信任你并将指针传递给LoadLibrary ,但是当被解释为一个宽字符串时,你传递的东西是无意义的。 It doesn't represent the name of any file on your system, so the API correctly reports that it cannot find the module. 它不代表系统上任何文件的名称,因此API会正确报告它找不到该模块。

你应该使用LoadLibrary(_T("ntdll.dll")) LPCWSTR只是将基于字符的字符串指针强制转换为宽带指针。

In addition to the necessity of converting the path string to wchar_t const* by using L prefix (which is already mentioned in the accepted answer). 除了必须使用L前缀(已在接受的答案中提到)将路径string转换为wchar_t const* According to my last couple of hours experience: 根据我最近几个小时的经验:
it worths mentioning that LoadLibrary function does not load the dependency(ies) of the intended library (DLL) automatically. 值得一提的是, LoadLibrary函数不会自动加载目标库(DLL)的依赖项。 In other word, if you try to load the library X which depends on the library Y, you should do LoadLibrary(Y) , then LoadLibrary(X) , otherwise loading the library X will fail and you will get error 126 . 换句话说,如果您尝试加载依赖于库Y的库X,则应该执行LoadLibrary(Y) ,然后执行LoadLibrary(X) ,否则加载库X将失败,您将收到错误126

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM