Home
Archives

.Net: PInvoke a Dll with a Dynamic Path

2/12/2008

I ran into an issue with some c# development that I should share.  We have a custom native C++ dll that has to be loaded at runtime and a function executed out of it.  This C++ dll is not in the same folder as the C# application, so just using DLLImport doesn't work.  What we needed was a way to dynamically, at run time, tell the DLLImport call where to load the C++ Dll from.  Unfortunately, it isn't built in, so we had to do some working around.

Essentially, I import the native kernel32.dll's LoadLibrary.  Using this we dynamically pass the path of the custome C++ dll to the LoadLibrary funtion.  This allows the dll to be loaded into our address space.  Any calls to the custom dll function will automagically work.  See below

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("CustomDll.dll", CharSet = CharSet.Auto)]
protected static extern bool RunFunction(string Path);

protected bool Launch(String sourceDir, String Path)
{
     String DllPath = sourceDir + "\\CustomDll.dll";

     if (LoadLibrary(DllPath).ToInt32() == 0) return false;

     return RunFunction(Path);
}