Get DLL path at runtime

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

    Here's a Unicode, revised version of the top voted answer:

    CStringW thisDllDirPath()
    {
        CStringW thisPath = L"";
        WCHAR path[MAX_PATH];
        HMODULE hm;
        if( GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | 
                                GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                (LPWSTR) &thisDllDirPath, &hm ) )
        {
            GetModuleFileNameW( hm, path, sizeof(path) );
            PathRemoveFileSpecW( path );
            thisPath = CStringW( path );
            if( !thisPath.IsEmpty() && 
                thisPath.GetAt( thisPath.GetLength()-1 ) != '\\' ) 
                thisPath += L"\\";
        }
        else if( _DEBUG ) std::wcout << L"GetModuleHandle Error: " << GetLastError() << std::endl;
    
        if( _DEBUG ) std::wcout << L"thisDllDirPath: [" << CStringW::PCXSTR( thisPath ) << L"]" << std::endl;       
        return thisPath;
    }
    

提交回复
热议问题