C# - Marshal.Copy:尝试读取或写入受保护的内存

时间:2013-06-03 10:41:16

标签: c# access-violation bmp

“尝试读取或写入受保护的内存。这通常表示其他内存已损坏。”

我在代码的 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.
 }

每当我处理第一张图片时,它都会给我错误 - 倒数第二,完全没问题。

我希望你能帮助我。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

你似乎正在考虑每排3倍的步幅;你的代码只适用于图像的前三分之一;在那之后你确实超出了你允许的范围。基本上是:

bmpData.Scan0 + y * bmpData.Stride * 3
看起来很狡猾。 “stride”每行使用的字节数(包括填充)。通常情况下,这只是:

bmpData.Scan0 + y * bmpData.Stride