C#調用haskell遭遇Attempted to read or write protected memory


1. Haskell的代碼如下:

haskell調用pandoc的代碼

上面的代碼中readMarkdown與writeHtmlString是pandoc中的函數,newString的作用是將String轉換為IO CString。

2. C語言的代碼如下:

調用pandoc的C語言代碼

上面的代碼是dll的調用入口。

3. ghc編譯出來的頭文件如下:

haskell ghc編譯出來的頭文件

4. 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;
    } 
}

5. 運行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.

  對應的中文錯誤信息:

嘗試讀取或寫入受保護的內存。這通常指示其他內存已損壞。

6. 而在ghci中執行直接執行haskell代碼能得到正確的結果:

被這個“Attempted to read or write protected memory. ”問題困擾了很長時間,一直未找到解決方法。

【更新】

后來找到了解決方法,詳見:困擾多日的C#調用Haskell問題竟然是Windows的一個坑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM