[問題] C++ 呼叫 C# DLL

看板C_Sharp作者 (區欠足易)時間8年前 (2015/12/29 11:45), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/1
各位好 目前我們公司所使用的資料庫是Oracle 8 使用的語言有 Oracle 的 D2K 以及 C# 現在的需求是我們有一些 C# 的 DLL 要使 D2K 中可以呼叫到這些DLL中的函式 而目前可行的做法是用 D2K 呼叫 C++ 的 DLL 因此我目前要做的就是使 C++ 能夠呼叫到 C# 的 DLL 然後使 D2K 透過 C++ 呼叫到 C# 的 DLL 而我是參考 MSDN 上一篇文章 How to call a managed DLL from native Visual C++ code in Visual Studio.NET 連結: https://support.microsoft.com/en-us/kb/828736 的作法,在使用到 INT 或 FLOAT DOUBLE 這種型別的函式都順利可用 唯有在使用到字串時會有問題 在 C++ 的參數為 LPWSTR (其實就是 wchar_t*) 我的作法是 將 C# 端的參數型別設為 ref StringBuilder 或 ref string 兩種都用過 執行時都會發生 "嘗試讀取或寫入受保護的記憶體。這通常表示其他記憶體已損毀。" 這種錯誤 而在 D2K 測試則會直接 CRASH 請問有人有類似經驗能提供處理方法嗎? 程式碼: C# DLL public int testString1(ref string output) { output += "C# testString1 ref string"; return 1; } public int testString2(ref StringBuilder output) { output.Append("C# testString1 ref StringBuilder"); return 1; } C++ DLL extern "C" _declspec(dllexport) int testStringCS1(LPWSTR output); int _declspec(dllexport) testStringCS1(LPWSTR output) { HRESULT hr = CoInitialize(NULL); ICalculatorPtr pICalc(__uuidof(ManagedClass)); long lResult; pICalc->testString1(&output, &lResult); CoUninitialize(); return 1; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.120.62.183 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1451360729.A.E6D.html

12/29 22:16, , 1F
COM Interop, 字串改BSTR試試
12/29 22:16, 1F
文章代碼(AID): #1MWW7Pvj (C_Sharp)