天天看點

WINDOWS下獲得DLL所在目錄的代碼

 擷取執行檔案所在目錄:

static char* getRunningPath(const char* pExe, char* pBuffer, const UINT appPathSize)
{
    if (GetModuleFileNameA(GetSelfModuleHandle(), pBuffer, appPathSize) == 0)
    {
        return NULL;
    }
    return pBuffer;
}      

如果要擷取加載的dll目錄呢?

//windows下擷取目前dll的句柄
static HMODULE GetSelfModuleHandle()
{
    MEMORY_BASIC_INFORMATION mbi;
    return ((::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0) ? (HMODULE)mbi.AllocationBase : NULL);
}
 
static char* getRunningPath(const char* pExe, char* pBuffer, const UINT appPathSize)
{
    if (GetModuleFileNameA(
        (pExe != NULL && strlen(pExe) > 0) ? NULL : GetSelfModuleHandle(),
        pBuffer, appPathSize) == 0)
    {
        return NULL;
    }
    return pBuffer;
}      

  如果有執行檔案,就擷取執行檔案的目錄,否則擷取so的目錄。

繼續閱讀