views:

1293

answers:

2

I have a .NET application and need to load a native library whose location is specified by the user. PInvoke looks like it'll only load from the global search paths (or a path specified at compile time?). Would the best method be to create a C++/CLI assembly which calls LoadLibrary at runtime?

Would C++/CLI be simpler than C# PInvoking LoadLibrary?

+5  A: 

If you already have a C#/VB.Net project it would be much simpler to just PInvoke LoadLibrary in order to get a DLL to load. It takes one quick PInvoke call from the existing dll

public partial class NativeMethods {

    /// Return Type: HMODULE->HINSTANCE->HINSTANCE__*
    ///lpLibFileName: LPCWSTR->WCHAR*
    [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint="LoadLibraryW")]
public static extern  System.IntPtr LoadLibraryW([System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string lpLibFileName) ;

}

Just adding this code would be much faster than adding a full C++\CLI project.

JaredPar
A: 

I agree with JaredPar. Once you have the dll loaded you'll need to access the API exposed by the dll using function pointers simple PInvoke declarations will not work any longer you will need to use the windows API GetProcAddress...

[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true)]
public static extern UIntPtr GetProcAddress(IntPtr hModule, string procName);

...and then bind the returned address to a delegate using GetDelegateForFunctionPointer() in the System.Runtime.InteropServices namespace.

SDX2000