可.NET的PInvoke动态加载从用户指定的目录中的本机DLL?本机、加载、动态、用户

2023-09-04 03:23:17 作者:缓缓消融而去

我有一个.NET应用程序和需要加载本机库被用户指定其位置。 PInvoke的看起来像它只会从全局搜索路径加载(或在编译时指定的路径?)。请问最好的方法是创建一个C ++ / CLI组件,它在运行时调用LoadLibrary?

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?

将为C ++ / CLI是比C#PInvoking调用LoadLibrary?

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

推荐答案

如果你已经有了一个C#/ VB.Net项目这将是非常简单的,只是调用LoadLibrary的PInvoke为了得到一个DLL加载。它需要一个快速的PInvoke呼叫从现有的DLL

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) ;

}

刚刚添加该code会比加入了全C ++ \ CLI项目要快得多。

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