Marshal.Copy: 嘗試讀取或寫入受保護的內存


注意事項: 本文中文內容可能為機器翻譯,如要查看英文原文請點擊上面連接.
 

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

我遇到此錯誤在我的代碼的Marshal.Copy部分。我相信我的數據不是損壞也不受保護。

我想知道在什么情況下這不會發生。我有列表 <> 的位圖。這僅發生在我處理的第一個索引 [0]。

因此,這里是怎么做到:-第一,我用[此代碼獲取位圖的像素數據]此代碼:

        Bitmap tmp_bitmap = BitmapFromFile[0];

        Rectangle rect = new Rectangle(0, 0, tmp_bitmap.Width, tmp_bitmap.Height);
        System.Drawing.Imaging.BitmapData bmpData =
            tmp_bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
            PixelFormat.Format24bppRgb);

        int length = bmpData.Stride * bmpData.Height;

        byte[] bytes = new byte[length];

        // Copy bitmap to byte[]
        Marshal.Copy(bmpData.Scan0, bytes, 0, length);
        tmp_bitmap.UnlockBits(bmpData);

 

它工作正常,沒有錯誤發生。

然后,我將應用此代碼[此操作將刪除像素數據線掃描填充]

 byte[] bytes = new byte[bmpData.Width * bmpData.Height * 3];
 for (int y = 0; y < bmpData.Height; ++y) {
 IntPtr mem = (IntPtr)((long)bmpData.Scan0 + y * bmpData.Stride * 3);
 Marshal.Copy(mem, bytes, y * bmpData.Width * 3, bmpData.Width * 3); //This is where the exception is pointed.
 }
每當我要處理的第一個圖像 — — 第二,最后,沒有問題在所有,它給我這一錯誤。

我希望你能幫我用這個。謝謝你在前進。

解決方法 1:

你似乎會考慮 3 倍的每一行 ; 步幅您的代碼將僅工作第一次第三次的圖像 ;之后,你確實有超出允許的范圍。基本上:

bmpData.Scan0 + y * bmpData.Stride * 3

看起來真的很不可靠。"跨越"使用的字節數 (包括填充) 通過每個行。只是通常情況下,就是:

bmpData.Scan0 + y * bmpData.Stride


免責聲明!

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



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