[問題]透過DllImport引用DLL出現記憶體損毀例外

看板C_Sharp作者 (這就是人生)時間17年前 (2009/02/05 21:43), 編輯推噓1(102)
留言3則, 1人參與, 最新討論串1/1
小弟透過C#去使用第三方(C/C++)的DLL時,遇到如下的例外訊息 攔截到 System.AccessViolationException Message="嘗試讀取或寫入受保護的記憶體。這通常表示其他記憶體已損毀。" 本以為是在包DLL時參數型態給定錯誤, 但其實該DLL的方法確實有成功執行(透過該DLL方法寫入的特定log檔得知) 不知道大家可以看一下我寫的程式是否有問題~~thx 目前比較懷疑回傳的型態,我用String去接,是否有誤... ----C#程式片段---------- [DllImport("dllbndclir.dll", SetLastError = true)] private unsafe static extern String msgCliFixConn( String senderID, String targetID, String basePath, String host, int port, int hbt, String profile, int errorCode, String Encode); string msgCliHdl = msgCliConn( "9700001", "9720001", "./Log", "192.168.11.11", 11122, 6, "setting.ini", 0, null); ---廠商提供的DLL說明(片段)------- ......... typedef char *msgCliHdl_t; ......... /** * Input * (略) * return * return NULL if failure -- msgCliHdl is not allocated. * Othereise, return allocated msgCliHdl. * */ msgCliHdl_t CallStack msgCliConn(char *senderID, char *targetID, char *basePath, char *host, int port, int hbt, char *profile, int errorCode, Char *Encode); -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.217.32.71

02/05 23:40, , 1F
我建議回傳值改用 IntPtr 接
02/05 23:40, 1F

02/05 23:40, , 2F
然後用 Marshal.PtrToStringAuto 之類的轉成 String
02/05 23:40, 2F

02/05 23:41, , 3F
但要先檢查回傳值是否 == IntPtr.Zero
02/05 23:41, 3F
文章代碼(AID): #19YkqN65 (C_Sharp)