LoadLibrary 返回 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);
}
我得到的输出是00000000
。根据 文档,函数失败时返回NULL。我尝试使用 GetLastError
,错误代码为 126(0x7e,未找到错误模组)。
我该如何纠正这个问题?
谢谢!
I just tried the following code(windows xp sp3, vs2010) and LoadLibrary seems to be returning 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
. According to the docs, NULL is returned when the function fails. I tried using GetLastError
and the error code is 126(0x7e, Error Mod Not Found).
How can I correct this issue?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您有一个由窄字符组成的字符串文字。您的 LoadLibrary 调用显然需要宽字符。类型转换并不是从一种类型转换为另一种类型的方法。使用
L
前缀获取宽字符串文字:类型转换告诉编译器您的
char const*
实际上是wchar_t const*
,这不是真的。编译器信任您,并将指针传递给 LoadLibrary,但是当解释为宽字符串时,您传递的内容是无意义的。它不代表系统上任何文件的名称,因此 API 正确报告它找不到该模块。You have a string literal, which consists of narrow characters. Your
LoadLibrary
call apparently expects wide characters. Type-casting isn't the way to convert from one to the other. Use theL
prefix to get a wide string literal:Type-casting tells the compiler that your
char const*
is really awchar_t const*
, which isn't true. The compiler trusts you and passes the pointer along toLoadLibrary
anyway, but when interpreted as a wide string, the thing you passed is nonsense. It doesn't represent the name of any file on your system, so the API correctly reports that it cannot find the module.您应该使用 LoadLibrary(_T("ntdll.dll")) LPCWSTR 只是将基于字符的字符串指针转换为宽字符串指针。
You should use
LoadLibrary(_T("ntdll.dll"))
LPCWSTR just casts char-based string pointer to widestring pointer.除了需要使用
L
前缀将路径string
转换为wchar_t const*
之外(已在接受的答案中提到)。根据我过去几个小时的经验:值得一提的是,
LoadLibrary
函数不会自动加载目标库 (DLL) 的依赖项。换句话说,如果您尝试加载依赖于库 Y 的库 X,您应该执行LoadLibrary(Y)
,然后执行LoadLibrary(X)
,否则加载库 X 将失败,您将收到错误126
。In addition to the necessity of converting the path
string
towchar_t const*
by usingL
prefix (which is already mentioned in the accepted answer). 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. In other word, if you try to load the library X which depends on the library Y, you should doLoadLibrary(Y)
, thenLoadLibrary(X)
, otherwise loading the library X will fail and you will get error126
.