Can .NET PInvoke dynamically load a native dll from a user specified directory?

为君一笑 提交于 2019-12-06 12:36:09

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!