gpt4 book ai didi

C# Attempted to read or write protected memory 错误

转载 作者:行者123 更新时间:2023-11-30 16:34:55 26 4
gpt4 key购买 nike

附录:当我取消选中“优化代码”时它似乎运行正确,这让我相信这是一些古怪的配置问题

首先,我尝试运行非托管代码。我检查了“允许不安全代码”。它指向这里的这行代码,我试图在不使用相对较慢的 getpixel 的情况下读取位图:

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

下面是完整的片段。我该如何解决这个问题?

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));
}
}
}

最佳答案

由于我们掌握的信息有限,很难说清楚,但我看到了几个明显的问题,其中一个直接解决了您的问题:

  1. 您没有检查像素格式,而是假设它是 32bppRGB。可能是 24bppRGB,这可以解释错误。

  2. 您读取的 RGB 值不正确; Windows 在内部以 BGR 顺序存储位图。

  3. 您没有在方法结束时调用 UnlockBits。

关于C# Attempted to read or write protected memory 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2233668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com