Get module entry by name from external program via WinAPI I'm asking myself if there's any better/shorter way of getting a module entry by its name from an external process.

This is the code I have so far:

MODULEENTRY32 GetModule(const char* ModuleName) {

    HANDLE Module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
    MODULEENTRY32 Entry;
    Entry.dwSize = sizeof(Entry);

    WCHAR *ModuleNameChar;
    int Chars = MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, NULL, 0);
    ModuleNameChar = new WCHAR[Chars];
    MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, (LPWSTR)ModuleNameChar, Chars);

    while (Module32Next(Module, &amp;Entry)) {
        if (!wcscmp((wchar_t*)Entry.szModule, ModuleNameChar)) {
            CloseHandle(Module);
            return Entry;
        }
    }

    /*
        Return the module base 0x0 if we don't find any module
    */
    CloseHandle(Module);
    Entry.modBaseAddr = 0x0;
    return Entry;
}


It should work but it's quite complicated. Is there any useful function or method I can make use of to simplify this whole thing?
Unfortunately, I'm not sure of any way of being more concise.

There are a few changes you could make, but they're mostly optional.


Check the return value of CreateToolhelp32Snapshot(). The documentation says the following:


  Includes all modules of the process specified in th32ProcessID in the
  snapshot. To enumerate the modules, see Module32First. If the function
  fails with ERROR_BAD_LENGTH, retry the function until it succeeds.


I use CreateToolhelp32Snapshot() in an application that runs 24/7 and I know for a fact that I get the ERROR_BAD_LENGTH error here and there. In my case, I cannot afford false negatives, so I have to put this function in a loop. If you are okay with having false-negatives occasionally, then I wouldn't worry too much about it.
I don't know if you're showing us the full code for this function, but you have a memory leak here:

ModuleNameChar = new WCHAR[Chars];

I don't see where you are deleting this buffer. I personally would use an std::vector&lt;WCHAR&gt; as a buffer, give it the correct size, and pass the address of the first element to MultiByteToWideChar().
If you use HANDLEs a lot, consider wrapping them in an RAII container. That way, you don't have to worry about closing them manually. This will also make your code exception-safe if you ever add any functions that can throw (you actually already have one that can throw, the new call).
I noticed you're not calling ::Module32First(). You probably don't need it, but I always have it anyway.
This is a personal preference, but I think your upper-case variable names look absolutely horrendous. Please use snake-case or camel-case for variable names.


There's really nothing helpful to say unfortunately, the Windows API can be quite cumbersome.