【发布时间】:2013-06-03 10:41:15
【问题描述】:
“试图读取或写入受保护的内存。这通常表明其他内存已损坏。”
我在代码的 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.
}
每当我处理第一张图像时,它都会给我这个错误 - 倒数第二个,完全没有问题。
我希望你能帮助我解决这个问题。 提前谢谢你。
【问题讨论】:
-
您在解锁后回信
bmpData。 -
@RogerRowland “我应用此代码”可能意味着“在
UnlockBits之前”
标签: c# access-violation bmp