[英]Access Violation when returning a value calling a C++ dll function from C#
我正在嘗試從 C# 調用 DLL 中的 C++ 函數。 這個函數的一個參數是一個指向短型變量的指針。
我沒有做任何花哨的數據結構或未知大小的變量。 只是一個簡單的短值。
當 DLL c++ 函數嘗試修改此變量的值時,它會給出“非托管異常 0xC0000005:訪問沖突”。
我無法修改 DLL 源代碼(它在其他項目中使用,我無法觸摸它,盡管我有調試它的源代碼)
c++ DLL函數的代碼(請注意代碼中的“//this line provokes the exception”注釋行)
// declaration
virtual TestFunction(short __RPC_FAR *sRet) = 0;
// definition
STDMETHODIMP CABTest::TestFunction(short *sReturnValue)
{
//some
//calculations
//here
*sReturnValue = 1; //this line provoques the exception
return 0;
}
調用 DLL 的 C# 代碼
[DllImport("test.dll", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern short TestFunction(ref short sReturn);
short sMyValue = 0;
TestFunction(ref sMyValue);
我希望 sMyValue 值為 1,因為我傳遞的引用是直接的短類型(不是花哨的數據結構),但我只遇到應用程序崩潰(上述例外)。
我可以在 C# 代碼中做些什么來避免這個問題? 我所看到的所有搜索類似問題都需要重寫 C++ 函數(將“short *sReturnValue”更改為“short **sReturnValue”,但我無法觸及原始 DLL 源代碼。
我想我會寫一個調用 test.dll 的 wrapper.dll,但我想知道是否有任何直接和更快的解決方案。
我按照@PaulMcKenzie 的建議創建了一個實例,並且運行良好。 我錯誤地認為我可以只獲取 DLL 並使用所需的計算函數,但我想我不能。 只是將這個答案留給可能犯同樣錯誤的其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.