View Comments

Recently a user in the irc channel I frequently visit had some trouble understanding this, so I decided it would be a simple thing to show that others could benefit. Using GetProcAddress is really quite simple, but the way you declare the function you're getting often looks alien to a beginner.


This is how you do it in C++ if you were to try and get the address for MessageBox. First you may find it easier to make a typedef that will be the "type" of your function (much like as if it were a variable).

typedef int(__stdcall *MESSAGEBOX)(HWND, LPCSTR, LPCSTR, UINT);

Really this is just the same function prototype of MessageBox, just organized a little differently.  I am going to go ahead and assume you've already used LoadLibrary and jump right into GetProcAddress.

MESSAGEBOX funcMessageBox = NULL; /* Declared as a variable, but we will use it just like a function after we get it's address. That's really what this is, just an address holder for the actual function in the library (a pointer). */
 funcMessageBox = reinterpret_cast<MESSAGEBOX> (::GetProcAddress(hModule, "MessageBoxA")); /* GetProcAddress returns VOID* so we need to recast that as the type we made for this function. We're using the multibyte version of MessageBox which is actually named MessageBoxA. */
 if(funcMessageBox == NULL) { return FALSE; } // You obviously want to make sure this was successful before using it. If it fails here then either you got the name of the function wrong (it's not always what you think it is) or LoadLibrary failed and hModule is probably just not valid.
 funcMessageBox(NULL, "Hello World", "GetProcAddress Test", MB_OK); /* This is how we call that function, just as it were any other function. Nothing special going on here. */

And that's basically all there is to it. Just make sure when you are done that you free that library you loaded. Also if you made your own library and have trouble figuring out what the actual name of the function is after it was linked into your DLL there are tools you can find online for that. Sometimes your function names get padded with extra stuff, which I don't think happens if this were just C. This is not the case usually with any functions you want to get from Windows libraries so you are usually safe just using the name you know it is with A or W as a suffix if needed.