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 ?
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
Source: Stackoverflow.com