【问题标题】:C# - Marshal.Copy : Attempted to read or write protected memoryC# - Marshal.Copy:试图读取或写入受保护的内存
【发布时间】: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


【解决方案1】:

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

bmpData.Scan0 + y * bmpData.Stride * 3

看起来真的很狡猾。 “步幅”每行使用的字节数(包括填充)。通常,这只是:

bmpData.Scan0 + y * bmpData.Stride

【讨论】:

  • 哦,你是对的!现在我的问题解决了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2010-12-27
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 2012-09-21
  • 2012-04-16
  • 2020-07-14
相关资源
最近更新 更多