Search code examples
cwindowsdllloadlibrarygetprocaddress

How to dynamically load every needed function


I'm trying to find a way to dynamically load every Windows API function I need to use. For example, to use a the printf function, I do something like:

#include <windows.h>

typedef int (*printfPtr)(const char *str, ...);
int main(){
    HMODULE handle = LoadLibraryA("crtdll.dll");
    if(handle == NULL) return;
    printfPtr printfAdr = (printfPtr)GetProcAddress(handle, "printf");
    (*printfAdr)("This is a test\n");
}

This is a fast coded working snippet. Doing this was easy because I followed a guide which told me that I could load the printf from the crtdll.dll. However, now I would like to load the CreateFileA function but I don't know how to find the correct dll to load.

I've already tried to Google something and searched on the MSDN but I didn't find anything. In general, given one function (a common one, for example one in windows.h, stdio.h or stdlib.h), how can I find which dll to load?

N.B. I know that some of you may think that loading function this way as no use. However, this is not the real program. In the real one, the addresses LoadLibraryA and GetProcAddress are manually found and I can write code and then export the segment from the PE.


Solution

  • The function in your example (printf) is not a Windows API function, rather it is a function defined in the C standard. Therefore it should be more readily available. However this re-enforces the point that if you don't have any of the either standard or Windows API functions available that makes for a lot of dlls to know about. I don't know of a single place that defines them all in one source file, but you can load your functions on a case by case basis using a resource like www.pinvoke.net which lets you type in a function name and retrieve the name of the dll to load (as well as the C# method signature but you don't need that, you already know the C signature).