Can .NET PInvoke dynamically load a native dll fro

2019-05-26 07:00发布

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?

2条回答
放我归山
2楼-- · 2019-05-26 07:32

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.

查看更多
地球回转人心会变
3楼-- · 2019-05-26 07:36

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.

查看更多
登录 后发表回答