繁体   English   中英

在VS内从C#调用C ++ DLL失败。 在VS外运行exe,它可以工作

[英]Calling C++ DLL from C# within VS fails. Run exe outside VS and it works

我有一个C ++ DLL,从C#控制台应用程序如下调用。

在Visual Studio中运行以进行调试时,它会抛出一个异常,说堆栈不稳定并检查方法参数是否正确。 但是,如果我从Windows资源管理器中运行VS外部的* .exe,它会按预期将数据返回到屏幕。

如何让它在Visual Studio中运行?

谢谢

**From the C++ header file:**
#ifdef RFIDSVRCONNECT_EXPORTS
#define RFID_CONN_API __declspec(dllexport)
#else
#define RFID_CONN_API __declspec(dllimport)
#endif

RFID_CONN_API BSTR rscListDevices( long showall ) ;


[DllImport("MyDLL.dll")]
[return: MarshalAs(UnmanagedType.BStr)]
public static extern string rscListDevices(int showall);

static void Main(string[] args)
{
  string data= rscListDevices(0);
  Console.WriteLine(data);
  Console.ReadKey();
}

首先,确保在C ++C#中使用相同的调用约定。

我怀疑/Gd编译器选项已设置(因为它是默认设置),因此__cdecl用作未标记函数的默认调用约定。

您可以通过在C#代码中指定相同的调用约定来修复崩溃:

[DllImport("MyDLL.dll", CallingConvention=CallingConvention.Cdecl))]
[return: MarshalAs(UnmanagedType.BStr)]
public static extern string rscListDevices(int showall);

或者将rscListDevices的调用约定更改为__stdcall (这是C#中的默认值):

RFID_CONN_API BSTR __stdcall rscListDevices( long showall ) ;

您还可以通过手动或使用“项目属性”对话框将编译器选项从/ Gd更改为/ Gz,将__stdcall设置为C ++ DLL中未标记函数的默认调用约定: 在Visual Studio中更改默认调用约定

但是,如果您确实要禁用MDA,可以进入Debug-> Exceptions并取消选中Managed Debugging Assistance。

您可以在此处此处阅读有关pInvokeStackImbalance和MDA的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM