Get DLL path at runtime

前端 未结 10 1416
梦谈多话
梦谈多话 2020-11-28 22:31

I want to get a dll\'s directory (or file) path from within its code. (not the program\'s .exe file path)

I\'ve tried a few methods I\'ve found:

10条回答
  •  天涯浪人
    2020-11-28 23:16

    Imho, Remy Lebau’s answer is the best, but lacks like all other answers to render the directory of the DLL. I quote the original question: “I want to get a dll's directory (or file) path from within its code. (not the program's .exe file path).”

    As Remy and Jean-Marc Volle pointed out, the DLL entry function DllMain usually contained in dllmain.cpp provides the handle to the DLL. This handle is often necessary, so it will be saved in a global variable hMod. I also add variables of type std::wstring to store the fully qualified name and the parent path of the DLL.

    HMODULE hMod;
    std::wstring PathAndName;
    std::wstring OnlyPath;
    BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
    {
      switch (ul_reason_for_call)
      {
        case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH:
           case DLL_PROCESS_DETACH:
         break;
      }
      hMod = hModule;
      const int BUFSIZE = 4096;
      wchar_t buffer[BUFSIZE];
      if (::GetModuleFileNameW(hMod, buffer, BUFSIZE - 1) <= 0)
      {
        return TRUE;
      }
    
      PathAndName = buffer;
    
      size_t found = PathAndName.find_last_of(L"/\\");
      OnlyPath = PathAndName.substr(0, found);
    
      return TRUE;
    }
    

    These global variables can be used inside the DLL.

提交回复
热议问题