The way this is done is by:
- Defining the prototype of the function (use MSDN for that)
- Loading the DLL (unless it is kernel32.dll) -> LoadLibrary
- Getting the handle of the module -> GetModuleHandle
- Getting the function address -> GetProcAddress
Stop here if you want to figure out how to actually code it
Table of Contents
- Defining the function’s prototype
- Loading the module
- Getting the function addy
- Calling the function
- Function from user32.dll
So let’s hop into coding!
Defining the function’s prototype
By checking the MSDN documentation we come across this prototype:
That green underline is due to VS not finding a definition of that function, ignore it.
WINAPI is just stdcall, a calling convention, I might write a post about those someday.
So, let’s arrange that, make it a function pointer and typedef:
Ps: Note that Asterisk after WINAPI, meaning it refers to a function pointer.
Now we write a variable of that type:
Keep in mind that writing the function pointer is optional but makes the code 100x cleaner and beautiful.
Loading the module
The next step is getting the handle of Kernel32.dll since that’s where CreateProcessW lies (you can find that out by the library requirement in the MSDN page), we don’t need to load it since it gets automatically loaded into every process:
Getting the function address
The final step before actually calling the function is to get the address of the function:
Calling the function
Now let’s call it!
Function from user32.dll
Now let’s try with MessageBoxW(not going to explain the steps since should be pretty clear from now):
Now, let’s run and…
Remember I said that we needed to load the DLL if we weren’t using a Kernel32 function? Yep, that’s right now instead of GetModuleHandle, we use LoadLibrary.
And now it works!
Now I hope you can call this native function “NtGetTickCount”:
The Nt implies it is from ntdll.dll since it is a native function
And that’s it! See? Not rocket science 😛