开发者

Attempted to read or write protected memory. This is often an indication that other memory is corrupt. C# Error

I am writing an imaging app in WPF C#. It reads the image file pixel by pixel using unsafe code.

The problem I am getting is it throws the error Attempted to read or write protected memory. This is often an indication that other memory is corrupt. when writing the pixel value. It works fine for some images and for others it shows the error. Following is the code:

unsafe
            {
                byte* pbuff = (byte*)buff.ToPointer();
                for (int i = 0; i < size; i=i+stride)
                  {
                        pbuff[i] = (byte)cr[j].NewColor.Blue;
                        pbuff[i + 1] = (byte)cr[j].NewColor.Green; // here it shows error
                        pbuff[i + 2] = (byte)cr[j].NewColor.Red;
                   }
            }

EDIT

Reading of the pixels works fine.

                B = (double)pbuff[i];
                G = (double)pbuff[i + 1];
                R = (double)pbuff[i + 2];

It does not show开发者_如何转开发s any error while reading but for the same index (that was read) it shows error when attempted to write.


Basically this means that you are trying to write to the memory outside the memory allocated for the object referenced by pbuff.

So this is basically the same as array index out of bounds in safe code.


If you're using WPF, you should not use unsafe code, but instead play nice with WPF. This is what the WriteableBitmap Class is for I think.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜