LoadLibrary returning Null

user277465 picture user277465 · Dec 22, 2011 · Viewed 9.1k times · Source

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!

Answer

Rob Kennedy picture Rob Kennedy · Dec 22, 2011

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 the L prefix to get a wide string literal:

LoadLibrary(L"ntdll.dll")

Type-casting tells the compiler that your char const* is really a wchar_t const*, which isn't true. 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. It doesn't represent the name of any file on your system, so the API correctly reports that it cannot find the module.