N/Direct - The .NET Interoperability Resource Center 

FAQ

 

 

 

Most Valuable Professional

How do I call functions in a DLL not in the default search path?
Written: 6/23/2002 Updated: 6/23/2002

You can load the DLL manually before the CLR tries to do it for you, using the LoadLibrary Win32 API. By passing it the fully qualified path, you can bypass the regular search path rules.

The following code calls the exported function MyFunc in unmanaged.dll, located in the ..\unmanaged directory relative to the executable.

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

[DllImport("unmanaged.dll")]
static extern int MyFunc(int i);

static void Main()
{
  // Ensure current directory is exe directory
  Environment.CurrentDirectory = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );

  string dllPath = Path.GetFullPath( @"..\unmanaged\unmanaged.dll" );
  LoadLibrary( dllPath );
  Console.WriteLine( MyFunc( 5 ) );
} 
    

VB.NET
Declare Auto Function LoadLibrary Lib "kernel32.dll" (ByVal lpFileName As String) As IntPtr

Declare Function MyFunc Lib "unmanaged.dll" (ByVal i As Integer) As Integer

Shared Sub Main()
  ' Ensure current directory is exe directory
  Environment.CurrentDirectory = Path.GetDirectoryName([Assembly].GetExecutingAssembly().Location)

  Dim dllPath As String = Path.GetFullPath("..\unmanaged\unmanaged.dll")
  LoadLibrary(dllPath)
  Console.WriteLine(MyFunc(5))
End Sub