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

爷,独闯天下 提交于 2019-12-08 03:00:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/530143/can-net-pinvoke-dynamically-load-a-native-dll-from-a-user-specified-directory

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