非托管DLL加载路径

时间:2012-11-07 09:45:04

标签: .net dll c++-cli

我有一个托管c ++ / cli项目,它包装了一个非托管的dll。

我使用LoadLibrary加载了非托管dll,但LoadLibrary调用无法找到我的dll。

  HMODULE theDllHell = LoadLibrary(L"mylib.dll");

我该怎么办,以便将我的dll复制到输出目录以及我必须提供给LoadLibrary的路径?

2 个答案:

答案 0 :(得分:1)

要从当前或exe目录加载库,只有库名,没有路径。有关完整的Dll搜索顺序,请参阅动态链接库搜索顺序http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586%28v=vs.85%29.aspx

The directory from which the application loaded.
The current directory.
The system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable. 

如果要将库复制到输出目录,请将此库项目添加到解决方案中。添加模块将在同一目录中。您还可以使用mylib项目中的Post-Build Step将mylib.dll复制到您需要的任何目录。

答案 1 :(得分:1)

首先:假设您已将DLL添加到项目中,并且它在SolutionExplorer面板中可见,只需右键单击它即可:

  • 在BuildAction中为“内容”
  • CopyLoOutputDir中的
  • 选择'CopyIfNewer'

如果我没有错误地记录这些选项,那么只要它合理,它现在应该被复制到输出目录。参考:http://msdn.microsoft.com/en-us/library/0c6xyb66.aspx

第二:LoadLibrary以传统的Windows特定顺序搜索一系列路径。您可以几乎的路径始终是:

  • 您当前的工作目录
  • 系统DLL目录,例如%windir%\ system32

请查看文档:{​​{3}}例如,您提到的'SetDllDirectory'非常有用。此外,这里是详细解释的搜索路径顺序:http://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx

编辑:当然你可以向LoadLibrary提供文件的CWD相对或完全绝对路径。这总能解决问题,但是 - 我不推荐它,因为当应用程序要在操作系统的各种版本和语言上运行时,手动确定路径可能不是一项简单的任务!