簡體   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