Sha*_*mer 7 c# dllimport windows-7
我想暂时将目录添加到DLL搜索路径 - 在Windows 7下有正确的方法吗?
脚本
我有一个C#应用程序,我们称之为WonderApp.
WonderApp需要调用位于的C++ DLL C:\MyPath.因此,作为WonderApp的一部分Program.Main(),我添加了以下命令:
Environment.SetEnvironmentVariable("PATH",
"C:\\MyPath;" + Environment.GetEnvironmentVariable("PATH"));
Run Code Online (Sandbox Code Playgroud)
根据这篇文章,添加一个目录PATH也应该将它添加到目录搜索DLL.
该解决方案在Windows XP中运行良好:如果我将目录添加到PATH,则加载DLL并且程序运行正常.如果我不添加目录,则DLL不会加载,失败并显示"未找到"错误.
但是,这不适用于Windows 7.
所以我想,让我们试试吧SetDllDirectory().像这样:
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetDllDirectory(string lpPathName);
Run Code Online (Sandbox Code Playgroud)
后来:
bool success = SetDllDirectory(Util.Paths.GetApplicationDataDir());
Run Code Online (Sandbox Code Playgroud)
的价值success是true,但DLL仍然不能加载.
最后,如果我在运行应用程序之前手动设置PATH为包含C:\MyPath- 它一切正常!DLL加载,运行得很好.
所以,要重新迭代:
是否有正确的方法将目录临时添加到Windows 7下的DLL搜索路径?
更新:使用Process Explorer,我检查了应用程序的运行时环境,"C:\ MyPath"确实在PATH!此外,我看到它Helper.dll位于打开句柄列表中(作为DLL,而不仅仅是文件) - 它仍然声称没有找到它.
我的解决方案很简单,但我觉得诉诸它很荒谬。
我编写了另一个程序集“Shell”,它修改环境、运行 WonderApp,然后退出。
通过在运行主应用程序 (WonderApp) 之前修改PATH,主应用程序的 DLL 搜索路径包括添加到修改后的PATH.
它看起来像这样:
namespace shell
{
static class program
{
[dllimport("kernel32.dll", charset = charset.auto, setlasterror = true)]
public static extern bool setenvironmentvariable(string lpname, string lpvalue);
private static string joinargstosinglestring(string[] args)
{
string s = string.empty;
for (int i = 0; i < args.length; ++i)
{
if (!string.isnullorempty(s))
{
s += " ";
}
s += "\"" + args[i] + "\"";
}
return s;
}
[stathread]
static void main(string[] args)
{
string pathbefore = environment.getenvironmentvariable("path");
string wewant = util.paths.getapplicationdatadir() + ";" + pathbefore;
setenvironmentvariable("path", wewant);
Process process = Process.Start(".\\WonderApp.exe", joinArgsToSingleString(args));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望我能找到更好的解决方案!
| 归档时间: |
|
| 查看次数: |
5502 次 |
| 最近记录: |