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

In fact, I got a C++ (working) DLL that I want to import into my C# project to call it's functions.

It does work when I specify the full path to the DLL, like this :

string str = "C:\\Users\\userName\\AppData\\Local\\myLibFolder\\myDLL.dll";
[DllImport(str, CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

The problem is that it's gonna be an installable project, so the user's folder will not be the same (ex : pierre, paul, jack, mum, dad, ...) depending computer/session where it'd be runned on.

So I'd like my code to be a little more generic, like this :

/* 
goes right to the temp folder of the user 
    "C:\\Users\\userName\\AppData\\Local\\temp"
then go to parent folder
    "C:\\Users\\userName\\AppData\\Local"
and finally go to the DLL's folder
    "C:\\Users\\userName\\AppData\\Local\\temp\\myLibFolder"
*/

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 
[DllImport(str, CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

The big deal is that "DllImport" desire a "const string" parameter for the DLL's directory.

So my question is :: What could be done in this case ?

This question is related to c# c++ dll constants dllimport

The answer is


DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.


If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.

EDIT

Here is a code snippet that works, and shows what I meant.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        var result = a.ShowMessage();
    }
}

class FunctionLoader
{
    [DllImport("Kernel32.dll")]
    private static extern IntPtr LoadLibrary(string path);

    [DllImport("Kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
    {
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));
    }
}

public class MyClass
{
    static MyClass()
    {
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
            FunctionLoader.LoadFunction<MessageBoxDelegate>(
                @"c:\windows\system32\user32.dll", "MessageBoxA");
    }

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
    {
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);
    }
}

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.


Even better than Ran's suggestion of using GetProcAddress, simply make the call to LoadLibrary before any calls to the DllImport functions (with only a filename without a path) and they'll use the loaded module automatically.

I've used this method to choose at runtime whether to load a 32-bit or 64-bit native DLL without having to modify a bunch of P/Invoke-d functions. Stick the loading code in a static constructor for the type that has the imported functions and it'll all work fine.


As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll would be present inside myLibFolder directory inside temporary folder of the current user.

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 

Now you can continue using the DllImport statement using a const string as shown below:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Just at run time before you call the DLLFunction function (present in C++ library) add this line of code in C# code:

string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 
Directory.SetCurrentDirectory(assemblyProbeDirectory);

This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory call sets the application's current working directory to the specified directory. If your myDLL.dll is present at path represented by assemblyProbeDirectory path then it will get loaded and the desired function will get called through p/invoke.


set the dll path in the config file

<add key="dllPath" value="C:\Users\UserName\YourApp\myLibFolder\myDLL.dll" />

before calling the dll in you app, do the following

string dllPath= ConfigurationManager.AppSettings["dllPath"];    
   string appDirectory = Path.GetDirectoryName(dllPath);
   Directory.SetCurrentDirectory(appDirectory);

then call the dll and you can use like below

 [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

If all fails, simply put the DLL in the windows\system32 folder . The compiler will find it. Specify the DLL to load from with: DllImport("user32.dll"..., set EntryPoint = "my_unmanaged_function" to import your desired unmanaged function to your C# app:

 using System;
using System.Runtime.InteropServices;

class Example
{
   // Use DllImport to import the Win32 MessageBox function.

   [DllImport ("user32.dll", CharSet = CharSet.Auto)]
   public static extern int MessageBox 
      (IntPtr hWnd, String text, String caption, uint type);

   static void Main()
   {
      // Call the MessageBox function using platform invoke.
      MessageBox (new IntPtr(0), "Hello, World!", "Hello Dialog", 0);    
   }
}

Source and even more DllImport examples : http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to dll

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer PHP 7: Missing VCRUNTIME140.dll How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'? WampServer: php-win.exe The program can't start because MSVCR110.dll is missing msvcr110.dll is missing from computer error while installing PHP installing JDK8 on Windows XP - advapi32.dll error The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there Loading DLLs at runtime in C# Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

Examples related to constants

Constants in Kotlin -- what's a recommended way to create them? Why Is `Export Default Const` invalid? Proper use of const for defining functions in JavaScript Declaring static constants in ES6 classes? How can I get the size of an std::vector as an int? invalid use of non-static member function Why does JSHint throw a warning if I am using const? Differences Between vbLf, vbCrLf & vbCr Constants Constant pointer vs Pointer to constant Const in JavaScript: when to use it and is it necessary?

Examples related to dllimport

How to use [DllImport("")] in C#? How can I specify a [DllImport] path at runtime? How to use <DllImport> in VB.NET? Is there any native DLL export functions viewer? Calling functions in a DLL from C++