Do you really need to do all the stuff you wrote? Getting the list of exported functions by a dll is not trivial, after getting the module address in memory you have to walk several data structures of the PE format, which is not so easy to do manually (although the DbgHelp functions automate most of the process).
On the other hand, if you just want to check if a dll is loaded and call one of its function the work gets easy.
If you don't care if the dll has to be loaded, just call LoadLibrary
and get the module handle; otherwise, call first GetModuleHandle
, which will provide you a handle to the module if is loaded, NULL
if it's not, and, if you want to continue, after that call LoadLibrary
(LoadLibrary
increments the reference count of the dll, so you're sure the dll won't get unloaded in the meantime).
Then, to check if the procedure you need is present and get its address, use GetProcAddress
; notice that usually C functions like the ones exported by Windows dlls are exported just by their name, not by their signature (in C overloading doesn't exist); if you want to call C++ procedures exported with decorated names you have to specify the mangled name.
GetProcAddress
will return you a pointer, that you'll have to cast to a function pointer with the correct signature of your function; now you're done, just use it to call the function and don't forget to call FreeLibrary
to decrement the reference counter to the dll.
Notice that all this stuff cannot be done safely from the inside of the DllMain
of your injected function; see here.