最近一直被C#調用Haskell時的“嘗試讀取或寫入受保護的記憶體”問題所困擾(詳見C#調用haskell遭遇Attempted to read or write protected memory,C#調用haskell時的“嘗試讀取或寫入受保護的記憶體”問題),而且困在其中,越陷超深,無法自拔,差點棄用C#解決我們面臨的問題。
問題是這樣的,只要在Haskell代碼中對字串進行操作,在C#調用時就會引發異常:
An unhandled exception of type 'System.AccessViolationException' occurred in Unknown Module.
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
樣本Haskell代碼如下:
如果直接返回字串,則一切正常,樣本Haskell代碼如下:
C#調用範例程式碼:
class Native{ [DllImport("libpandoc", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] public static extern IntPtr markdownToHtml(byte[] markdown);} public class Processor { public string Process(string text) { var intPtr = Native.markdownToHtml(System.Text.Encoding.UTF8.GetBytes(text)); var html = Marshal.PtrToStringAnsi(intPtr); return html; } }