Get DLL path at runtime

前端 未结 10 1413
梦谈多话
梦谈多话 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:06

    Provided you implemented the following dll entry point: (usually dllmain.cpp)

    BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
    

    You can simply do:

    switch (ul_reason_for_call)
    { 
    case DLL_PROCESS_ATTACH:
    {
        TCHAR dllFilePath[512 + 1] = { 0 };
        GetModuleFileNameA(hModule, dllFilePath, 512)
    }
        break;
    case DLL_THREAD_ATTACH: break;
    ...
    

    dllFilePath will then contain the path to where the current dll code was loaded. In this case hModule is passed by the process loading the dll.

提交回复
热议问题