c++ - 在运行时获取 DLL 路径

标签 c++ dll

我想从其代码中获取 dll 的 目录(或文件)路径。 (不是程序的.exe文件路径)

我尝试了一些我发现的方法:
GetCurrentDir - 获取当前目录路径。
GetModuleFileName - 获取可执行文件的路径。

那么我怎样才能找出代码在哪个dll中呢?
我正在寻找类似于 C# 的 Assembly.GetExecutingAssembly

的东西

最佳答案

您可以使用 GetModuleHandleEx 函数获取 DLL 中静态函数的句柄。你会发现更多信息here .

之后,您可以使用 GetModuleFileName 从刚刚获得的句柄中获取路径。有关该电话的更多信息是here .

一个完整的例子:

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.

关于c++ - 在运行时获取 DLL 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6924195/

相关文章:

c# - VBA C# DLL 未注册

.net - 在表单加载时将引用的 DLL 复制到本地目录

c++ - 如何使用 STL 将结构 vector 转换为映射

python - 来自 python 的 Cpp 编译失败但不在 shell 中

c++ - 使用 boost 将几何体切割成碎片

c++ - 启动使用附加库的可执行程序

dll - 如何根据给定的 CLSID 查找 DLL?

c++ - strtok 或 std::istringstream

c++ - 为iOS生成AWS-SDK-CPP时在cmake上损坏的CXX编译器错误

wpf - 未找到部署的应用程序的 MEF 部件,但在 Debug模式下找到