天天看点

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的目录。

继续阅读