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

标签 c# c++ .net dll assemblies

我正在尝试从我的 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);
}

最佳答案

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

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

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

关于c# - 在 C# 应用程序中调用 C++ DLL 函数时如何修复从上下文加载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015697/

相关文章:

c# - __VIEWSTATE 和 __EVENTVALIDATION 是否可以用于研究以破坏网络应用程序?

c# - 有没有更好的方法来用通用数学实例化常量?

c++ - vector 堆排序

c++ - 如何将 C 字符串数组传递给函数

c++ - 与用户构建的类似字符串类型的字符串比较

.net - Docker 构建镜像失败 - 没有这样的文件或目录

.NET SOAP 常见类型

c# - .NET Core 中的 Thread.Sleep 替代方案

c# - TPL 数据流如何删除 block 之间的链接

c# - 承包商改变代码风格