GetProcAddress Returns 0

I have this:

1
2
3
4
DWORD XER = (DWORD)GetProcAddress(GetModuleHandle(L"user32.dll"),"SendMessageW");

cout << XER << endl;


but XER returns 0 or NULL :( what is my mistake? i am using VC++
Last edited on
First Check out if GetModuleHandle() returns the expected value:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms683199%28v=vs.85%29.aspx

Maybe the "user32.dll" isn't loaded at that time


use GetLastError():

http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360%28v=vs.85%29.aspx

to find out more about the error
I've never seen GetProcAddress uses this way. For your code to succeed the DLL must've already been loaded in the process address space, so why don't you call the function directly ?

I always use LoadLibrary with GetProcAddress().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// A simple program that uses LoadLibrary and 
// GetProcAddress to access myPuts from Myputs.dll. 
 
#include <windows.h> 
#include <stdio.h> 
 
typedef int (__cdecl *MYPROC)(LPWSTR); 
 
int main( void ) 
{ 
    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 
 
    // Get a handle to the DLL module.
 
    hinstLib = LoadLibrary(TEXT("MyPuts.dll")); 
 
    // If the handle is valid, try to get the function address.
 
    if (hinstLib != NULL) 
    { 
        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts"); 
 
        // If the function address is valid, call the function.
 
        if (NULL != ProcAdd) 
        {
            fRunTimeLinkSuccess = TRUE;
            (ProcAdd) (L"Message sent to the DLL function\n"); 
        }
        // Free the DLL module.
 
        fFreeResult = FreeLibrary(hinstLib); 
    } 

    // If unable to call the DLL function, use an alternative.
    if (! fRunTimeLinkSuccess) 
        printf("Message printed from executable\n"); 

    return 0;

}

L"user32.dll"),"SendMessageW"

I see the problem.
That is not a problem if the code compiles (as it is the case here). Of course, the code will only work in Unicode builds.

Anyway this code will work:

1
2
3
4
5
6
7
8
9
10
typedef LRESULT (WINAPI *PFN)(HWND, UINT, WPARAM, LPARAM);
PFN MySendMessageW;
MySendMessageW = (PFN) GetProcAddress(
      GetModuleHandle(TEXT("user32.dll")), 
      "SendMessageW");
if (NULL != MySendMessageW) {
//call MySendMessageW() here like usual SendMessageW() API function
}

Topic archived. No new replies allowed.