有什么原因会导致Visual Studio 2013中的“vshost32.exe已停止工作”?

5
我正在开发的一个C# WPF应用程序包含许多调用未托管的外部DLL的操作。当正常运行应用程序时(即在Visual Studio调试器之外),所有对DLL的调用都能按预期工作。但是,当在Visual Studio 2013中进行调试时,对DLL中特定方法的调用会导致应用程序崩溃:

vshost32.exe has stopped working

这是我导入该方法的方式:

[DllImport("Client.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern string ClientGetVersion();

...这是我调用DLL方法的方式:

try
{
  version = ClientGetVersion();
}
catch (Exception ex)
{
  // Error handling omitted for clarity...
}

看起来Visual Studio在调试会话期间使用vshost32.exe进程来托管应用程序(VSHOST - the Hosting Process)。此外,“当启用托管进程时,对某些API的调用可能会受到影响。在这些情况下,需要禁用托管进程以返回正确的结果。”(请参见MSDN文章How to: Disable the Hosting Process)。如下所示,在“项目”>“属性”...>“调试”中禁用“启用Visual Studio托管进程”选项确实可以解决问题:

enter image description here

有人知道是什么原因导致“对特定API的调用”出现了问题吗?


1
只需修复代码中的错误。返回类型不能是字符串,必须是IntPtr。然后使用Marshal.PtrToStringAnsi()来恢复字符串。 - Hans Passant
感谢 @HansPassant 的快速回复 - 那解决了! - YetMoreStuff
2个回答

1
“vshost32.exe”错误是由于不正确的DllImport语句引起的 - 外部DLL的返回类型不能是字符串,而必须是IntPtr。
以下是更正后的代码:
[DllImport("Client.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ClientGetVersion();

...这是修订后的调用DLL方法:

string version;

try
{
  version = Marshal.PtrToStringAnsi(ClientGetVersion());

}
catch (Exception ex)
{
  // Error handling omitted for clarity...
}

感谢 @HansPassant 的答案。

0

退出 Visual Studio 并以管理员模式重新启动。它有效!!!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接