Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing path to externals assembly native dll dependecy

Tags:

c#

pinvoke

I have C# application which loads set of 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 :/

like image 488
sszarek Avatar asked Nov 26 '22 13:11

sszarek


1 Answers

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 ...
like image 71
James Wilkins Avatar answered Dec 22 '22 00:12

James Wilkins