C # Trying to read or write protected memory

Addendum: it seems to work correctly when I lower the "code optimization", which makes me think that this is some kind of fancy configuration problem

Firstly, I am trying to run unmanaged code. I have "allow unsafe code." He points to this line of code here, where I am trying to read a bitmap without using a relatively slow getpixel:

byte[] buff = { scanline[xo], scanline[xo + 1], scanline[xo + 2], 0xff };

Below is the entire snippet. How can I fix this problem?

private const int PIXELSIZE = 4;              // Number of bytes in a pixel

BitmapData mainImageData = mainImage.LockBits(new Rectangle(0, 0, mainImage.Width, mainImage.Height), ImageLockMode.ReadOnly, mainImage.PixelFormat);
List<Point> results = new List<Point>();

foundRects = new List<Rectangle>();

for (int y = 0; y < mainImageData.Height
{
        byte* scanline = (byte*)mainImageData.Scan0 + (y * mainImageData.Stride);

        for (int x = 0; x < mainImageData.Width; x++)
        {
            int xo = x * PIXELSIZE;
            byte[] buff = { scanline[xo], scanline[xo + 1], 
                    scanline[xo + 2], 0xff };
            int val = BitConverter.ToInt32(buff, 0);

            // Pixle value from subimage in desktop image
            if (pixels.ContainsKey(val) && NotFound(x, y))
            {
                Point loc = (Point)pixels[val];

                int sx = x - loc.X;
                int sy = y - loc.Y;
                // Subimage occurs in desktop image 
                if (ImageThere(mainImageData, subImage, sx, sy))
                {
                    Point p = new Point(x - loc.X, y - loc.Y);
                    results.Add(p);
                    foundRects.Add(new Rectangle(x, y, subImage.Width,
                                                               subImage.Height));
                }
          }
        }
+3
source share
3 answers

It’s hard to say with limited information what we have, but I see a couple of obvious problems, one of which directly relates to your problem:

  • , , 32bppRGB. , 24bppRGB, .

  • RGB; Windows BGR.

  • UnlockBits .

+3

xo + 1 xo + 2, x mainImageData.Width - 1? , , .

0

, 32bpp. 24bpp, , , 8 16 .

PIXELSIZE PixelFormat, - 4.

, , Stride, .

0

Source: https://habr.com/ru/post/1732114/


All Articles