开发者

Providing path to externals assembly native dll dependecy

I have C# application which loads set 开发者_如何学JAVAof managed assemblies. One of this assemblies loads two native dlls (each of them in different location) if they are avaiable. Iam trying to find way to provide search path to those native dlls.

Are there other options? I really dont want to provide those dlls with my software - copying them to programs directory of course solves the problem.

I've tried using SetDllDirectory system function but it is possible to provide only one path using it. Each call to this function resets path.

Setting PATH enviroment variable does not solve the problem too :/


I know this was an old post, but just so there's an answer: Using the LoadLibary function you can force load a native DLL:

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

You must call this before any other DLL does - I usually call it in a static constructor of my main program. I had to do this for DllImport(), and static constructors were always executed before the native DLLs were loaded - they only load actually the first time an imported function is called.

Example:

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

Once the library is loaded it should satisfy the DllImports() of the other managed assemblies you are loading. If not, they might be loaded using some other method, and you may have no other option but to copy them locally.

Note: This is a Windows solution only. To make this more cross-platform you'd have to detect operating systems yourself and use the proper import; for example:

    [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 ...


This could help:

    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;
    }


Register yours dlls to GAC. More here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜