提供外部程序集本机dll依赖的路径

本文关键字:依赖 路径 dll 本机 外部 程序集 | 更新日期: 2023-09-27 17:58:06

我有一个C#应用程序,它加载一组托管程序集。其中一个程序集加载两个本机dll(每个都位于不同的位置)(如果它们可用的话)。我正在设法为那些原生dll提供搜索路径。

还有其他选择吗?我真的不想在我的软件中提供那些dll——把它们复制到程序目录当然可以解决问题。

我尝试过使用SetDllDirectory系统函数,但使用它只能提供一个路径。对该函数的每次调用都会重置路径。

设置PATH环境变量也不能解决问题:/

提供外部程序集本机dll依赖的路径

我知道这是一篇旧文章,但有一个答案:使用LoadLibary函数,您可以强制加载本地DLL:

public static class Loader
{
    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string fileName);
}

你必须在任何其他DLL之前调用它——我通常在主程序的静态构造函数中调用它。我必须为DllImport()执行此操作,并且静态构造函数总是在加载本机DLL之前执行——它们实际上只是在第一次调用导入函数时才加载。

示例:

class Program
{
    static Program()
    {
       Loader.LoadLibrary("path'to'native1.dll");
       Loader.LoadLibrary("otherpath'to'native2.dll");
    }
}

加载库后,它应该满足正在加载的其他托管程序集的DllImports()。如果没有,则可能会使用其他方法加载它们,并且您可能别无选择,只能在本地复制它们。

注意:这只是一个Windows解决方案。为了使这个平台更加跨平台,你必须自己检测操作系统并使用正确的导入;例如:

    [DllImport("libdl")] 
    public static extern IntPtr DLOpen(string fileName, int flags);
    [DllImport("libdl.so.2")]
    public static extern IntPtr DLOpen2(string fileName, int flags);
    // (could be "libdl.so.2" also: https://github.com/mellinoe/nativelibraryloader/issues/2#issuecomment-414476716)
    // ... etc ...

这可能会有所帮助:

    private void Form1_Load(object sender, EventArgs e)
    {
        //The AssemblyResolve event is called when the common language runtime tries to bind to the assembly and fails.
        AppDomain currentDomain = AppDomain.CurrentDomain;
        currentDomain.AssemblyResolve += new ResolveEventHandler(currentDomain_AssemblyResolve);
    }
    //This handler is called only when the common language runtime tries to bind to the assembly and fails.
    Assembly currentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        string dllPath = Path.Combine(YourPath, new AssemblyName(args.Name).Name) + ".dll";
        return (File.Exists(dllPath))
            ? Assembly.Load(dllPath)
            : null;
    }

将您的dll注册到GAC。点击此处了解更多信息。