[英]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();
}
我懷疑/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中未標記函數的默認調用約定:
但是,如果您確實要禁用MDA,可以進入Debug-> Exceptions並取消選中Managed Debugging Assistance。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.