Load native libraries from a dynamic location

 
 
  • Gérald Barré

Recently, I had to solve an uncommon problem: download a native library (DLL) into a temporary directory outside the application folder, then call its methods from managed code. Since the DLL's exports are known in advance, I wanted to use the DllImport attribute to call them directly.

The application targets Windows 10, so I can rely on AddDllDirectory, a function introduced in Windows 8. It lets you register additional search paths for native libraries, so after downloading the DLL you simply call AddDllDirectory with its containing directory before invoking any of its methods.

C#
const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000;

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDefaultDllDirectories(uint DirectoryFlags);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int AddDllDirectory(string NewDirectory);

void Initialize()
{
    var downloadDirectory = "temp";
    DownloadDll(downloadDirectory);

    // Indicate to search libraries in
    // - application directory
    // - paths set using AddDllDirectory or SetDllDirectory
    // - %windows%\system32
    SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);

    // Add the directory of the native dll
    AddDllDirectory(downloadDirectory);

    // Use the native dll
    MyMethod();
}

[DllImport("mydll.dll")]
public static extern int MyMethod();

More information about the kernel32 methods:

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?