簡體   English   中英

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

[英]C# - Marshal.Copy : Attempted to read or write protected memory

“試圖讀取或寫入受保護的內存。這通常表明其他內存已損壞。”

我在代碼的Marshal.Copy部分遇到此錯誤。 我相信我的數據沒有被破壞也沒有受到保護。

我想知道這種情況會發生在什么情況下。 我有一個List <>的位圖。 這僅在我處理第一個索引[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.
 }

每當我處理第一張圖片時它都會給我錯誤 - 倒數第二,完全沒問題。

我希望你能幫助我。 先感謝您。

你好像每排都要考慮3倍的步伐; 你的代碼只適用於圖像的前三分之一; 之后你確實超出了你允許的范圍。 基本上:

bmpData.Scan0 + y * bmpData.Stride * 3

看起來很狡猾。 “stride” 每行使用的字節數(包括填充)。 通常情況下,這只是:

bmpData.Scan0 + y * bmpData.Stride

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM