在 C# 应用程序中调用 C++ DLL 函数时如何修复从上下文加载错误

How to Fix Load From Context Error when Calling C++ DLL Function in C# Application

我正在尝试从我的 C# 应用程序调用 dll 中的 C++ 函数。 dll 来自将安装在用户机器上的程序,因此必须在运行时加载 dll。我收到以下异常:

Managed Debugging Assistant 'LoadFromContext' has detected a problem ...

Additional information: The assembly named 'Client.API' was loaded from '(path to dll file)' using the LoadFrom context. The use of this context can result in unexpected behavior for serialization, casting and dependency resolution. In almost all cases, it is recommended that the LoadFrom context be avoided. This can be done by installing assemblies in the Global Assembly Cache or in the ApplicationBase directory and using Assembly.Load when explicitly loading assemblies.

我不太明白这个错误是什么意思。而且我不知道如何解决我的情况。我在网上搜索过,但没有找到非常有用的信息。 这是我正在使用的代码:

[DllImport("dmawin.dll")] 
private static extern int LoginDialog(IntPtr pWndParent, string pStrTitle, 
uint pFlags, [MarshalAs(UnmanagedType.LPWStr)] ref StringBuilder pStrDataSource, 
int pDSLength, string pStrUsername, string pStrPassword, string pStrSchema);


private bool Login(string pDataSource, string pLoginName, 
string pPassword, string pScheme)
{
    private const int MAX_DB_NAME = 256;
    IntPtr handle = ParentForm.Handle;
    var sb = new StringBuilder(pDataSource, MAX_DB_NAME);

    //function call
    LoginDialog(handle, null, flags, ref sb, MAX_DB_NAME, pLoginName, 
    pPassword, pScheme);
}

你看到的也不例外。这只是调试器显示的警告。如果你 运行 没有调试的应用程序,这根本不会出现。在调试器的异常处理设置中 Visual Studio,您可以禁用这些类型的警告。

修复您的调试器设置,应该关闭此警告。这个 MDA 通常只是为了警告程序员,当他不想使用 Assembly.LoadFrom() 时。由于您无法对此做任何事情,而不是您的代码,因此您几乎没有理由关注它。

在 VS2015 中使用调试 > Windows > 异常设置。在早期版本中,使用调试 > 异常。展开托管调试助手并取消勾选 "LoadFromContext"。如果您出于某种原因勾选了所有内容,那么您想要重置所有设置,请单击顶部节点两次。

FWIW,您使用的库显然已经用 .NET 语言编写。您很可能想与作者交谈并询问他是否支持托管接口,这样您就不必使用 [DllImport]。