user277465
user277465

Reputation:

LoadLibrary returning Null

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!

Upvotes: 3

Views: 10221

Answers (3)

Mohammed Noureldin
Mohammed Noureldin

Reputation: 16906

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). 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 do LoadLibrary(Y), then LoadLibrary(X), otherwise loading the library X will fail and you will get error 126.

Upvotes: 0

Pavel Zhuravlev
Pavel Zhuravlev

Reputation: 2791

You should use LoadLibrary(_T("ntdll.dll")) LPCWSTR just casts char-based string pointer to widestring pointer.

Upvotes: 2

Rob Kennedy
Rob Kennedy

Reputation: 163317

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.

Upvotes: 12

Related Questions