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.