How to Specify a [Dllimport] Path At Runtime

How can I specify a [DllImport] path at runtime?

Contrary to the suggestions by some of the other answers, using the DllImport attribute is still the correct approach.

I honestly don't understand why you can't do just like everyone else in the world and specify a relative path to your DLL. Yes, the path in which your application will be installed differs on different people's computers, but that's basically a universal rule when it comes to deployment. The DllImport mechanism is designed with this in mind.

In fact, it isn't even DllImport that handles it. It's the native Win32 DLL loading rules that govern things, regardless of whether you're using the handy managed wrappers (the P/Invoke marshaller just calls LoadLibrary). Those rules are enumerated in great detail here, but the important ones are excerpted here:

Before the system searches for a DLL, it checks the following:

  • If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.
  • If the DLL is on the list of known DLLs for the version of Windows on which the application is running, the system uses its copy of the known DLL (and the known DLL's dependent DLLs, if any). The system does not search for the DLL.

If SafeDllSearchMode is enabled (the default), the search order is as follows:

  1. The directory from which the application loaded.
  2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  5. The current directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

So, unless you're naming your DLL the same thing as a system DLL (which you should obviously not be doing, ever, under any circumstances), the default search order will start looking in the directory from which your application was loaded. If you place the DLL there during the install, it will be found. All of the complicated problems go away if you just use relative paths.

Just write:

[DllImport("MyAppDll.dll")] // relative path; just give the DLL's name
static extern bool MyGreatFunction(int myFirstParam, int mySecondParam);

But if that doesn't work for whatever reason, and you need to force the application to look in a different directory for the DLL, you can modify the default search path using the SetDllDirectory function.

Note that, as per the documentation:

After calling SetDllDirectory, the standard DLL search path is:

  1. The directory from which the application loaded.
  2. The directory specified by the lpPathName parameter.
  3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

So as long as you call this function before you call the function imported from the DLL for the first time, you can modify the default search path used to locate DLLs. The benefit, of course, is that you can pass a dynamic value to this function that is computed at run-time. That isn't possible with the DllImport attribute, so you will still use a relative path (the name of the DLL only) there, and rely on the new search order to find it for you.

You'll have to P/Invoke this function. The declaration looks like this:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

How to select the path for DllImport at run-time when the name of the required DLL can change?

An easy way is to ensure that the DLLs have the same file name (e.g. MyNativeLibrary.dll) and store them in separate sub-folders, e.g.:

  • x86\MyNativeLibrary.dll for the 32-bit DLL
  • x64\MyNativeLibrary.dll for the 64-bit DLL

When declaring your P/Invoke methods, you use the name of the library without specifying a hard-coded path e.g.:

public static class MyUtilityClass
{
[DllImport("MyNativeLibrary.dll")]
public static extern int DoSomething(int x, int y);
}

Finally, at the start if your application use NativeLibrary.Load(string) passing in the full path of the DLL you wish to load. This has to be done before attempting to call any function of your DLL.

// Pseudo-code. You might need to adapt to find the path where your DLLs are located

// Get the folder path where the current `App.exe` is located
var startupPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);

// Assume the DLL is in a sub-folder of the folder where `App.exe` is located
var myLibraryFullPath = Environment.Is64BitProcess
? Path.Combine(startupPath, @"x64\MyNativeLibrary.dll")
: Path.Combine(startupPath, @"x86\MyNativeLibrary.dll");

// Load the appropriate DLL into the current process
NativeLibrary.Load(myLibraryFullPath);

Once an unmanaged DLL is loaded into the process, any future P/Invokes decorated with [DllImport("MyNativeLibrary.dll")] will bind to the already-loaded DLL, so that's why it works.

DLLImport path C#

You can simply use relative urls like:

[DllImport("DLLWrap.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?DivSet@MyCall@MyFunc@@SAPADPAD@Z")]

Your application will search working directory (your local folder) for the file by default.

In Winforms, you can always ensure it uses your Working Directory by

[DllImport(Application.StartupPath + "\\DLLWrap.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?DivSet@MyCall@MyFunc@@SAPADPAD@Z")]

Specify the search path for DllImport in .NET

Call SetDllDirectory with your additional DLL paths before you call into the imported function for the first time.

P/Invoke signature:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

To set more than one additional DLL search path, modify the PATH environment variable, e.g.:

static void AddEnvironmentPaths(string[] paths)
{
string path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
path += ";" + string.Join(";", paths);

Environment.SetEnvironmentVariable("PATH", path);
}

There's more info about the DLL search order here on MSDN.


Updated 2013/07/30:

Updated version of the above using Path.PathSeparator:

static void AddEnvironmentPaths(IEnumerable<string> paths)
{
var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };

string newPath = string.Join(Path.PathSeparator.ToString(), path.Concat(paths));

Environment.SetEnvironmentVariable("PATH", newPath);
}

Dll import path . how to get dll path which located in other folder

  1. In the 'Solution Explorer', right click on 'References'.
  2. Click 'Add Reference'.
  3. Select the 'Browse' tab and select your 3rdparty.dll.
  4. After its added, right click the 3rdparty.dll under 'References' and change 'Copy Local' to true.
  5. Then just specify your DllImport like normal [DllImport("3rdparty.dll")]

This will only work if its a .NET assembly. Since it looks like you are using a C++ DLL, you will need to look at Using C++ Class DLL in C# Application



Related Topics



Leave a reply



Submit