Get DLL path at runtime

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

    You can use the GetModuleHandleEx function and get the handle to a static function in your DLL. You'll find more information here.

    After that you can use GetModuleFileName to get the path from the handle you just obtained. More information on that call is here.

    A complete example:

    char path[MAX_PATH];
    HMODULE hm = NULL;
    
    if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | 
            GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            (LPCSTR) &functionInThisDll, &hm) == 0)
    {
        int ret = GetLastError();
        fprintf(stderr, "GetModuleHandle failed, error = %d\n", ret);
        // Return or however you want to handle an error.
    }
    if (GetModuleFileName(hm, path, sizeof(path)) == 0)
    {
        int ret = GetLastError();
        fprintf(stderr, "GetModuleFileName failed, error = %d\n", ret);
        // Return or however you want to handle an error.
    }
    
    // The path variable should now contain the full filepath for this DLL.
    

提交回复
热议问题