提供到外部组件本机dll依赖的路径

问题描述

| 我有C#应用程序,它加载一组托管程序集。如果可用,则其中一个程序集将加载两个本机dll(每个dll都位于不同的位置)。 Iam试图找到方法来提供那些本机dll的搜索路径。 还有其他选择吗?我真的不想为这些dll提供我的软件-将它们复制到program目录中当然可以解决问题。 我已经尝试过使用SetDllDirectory系统功能,但是可以仅使用它提供一个路径。每次对该函数的调用都会重置路径。 设置PATH环境变量也不能解决问题:/     

解决方法

        这可以帮助:
    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;
    }
    ,        我知道这是一篇老文章,但是有一个答案:使用
LoadLibary
函数,您可以强制加载本机DLL:
public static class Loader
{
    [DllImport(\"kernel32.dll\")]
    public static extern IntPtr LoadLibrary(string fileName);
}
您必须先调用此函数,然后再执行其他DLL-我通常在主程序的静态构造函数中调用它。我必须为“ 3”做这件事,并且静态构造函数总是在加载本机DLL之前执行-它们仅在第一次调用导入的函数时才实际加载。 例:
class Program
{
    static Program()
    {
       Loader.LoadLibrary(\"path\\to\\native1.dll\");
       Loader.LoadLibrary(\"otherpath\\to\\native2.dll\");
    }
}
加载库后,它应满足要加载的其他托管程序集的“ 5”。如果不是,则可以使用其他方法加载它们,并且您别无选择,只能在本地复制它们。 注意:这仅是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 ...
    ,        将您的dll注册到GAC。这里更多。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...