附录:当我取消选中“优化代码”时,它似乎可以正常运行,这使我相信这是一些古怪的配置问题首先,我试图运行非托管代码.我检查了“允许不安全的代码”.它指向此行代码,在这里我尝试在不使用相对较慢的getpixel的情况下...

附录:当我取消选中“优化代码”时,它似乎可以正常运行,这使我相信这是一些古怪的配置问题
首先,我试图运行非托管代码.我检查了“允许不安全的代码”.它指向此行代码,在这里我尝试在不使用相对较慢的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));
}
}
}
解决方法:
有限的信息很难说,但是我看到了几个明显的问题,其中一个直接解决了您的问题:
>您不在检查像素格式,而是假设它是32bppRGB.可能是24bppRGB,这可以解释该错误.
>您读取的RGB值不正确; Windows在内部以BGR顺序存储位图.
>您不会在方法末尾调用UnlockBits.
织梦狗教程
本文标题为:C#尝试读取或写入受保护的内存错误


基础教程推荐
猜你喜欢
- c#中利用Tu Share获取股票交易信息 2023-03-03
- C#字体池技术实现代码详解 2023-02-03
- C# 实现与现有.NET事件桥接简单实例 2022-11-04
- C#利用ASP.NET Core开发学生管理系统详解 2023-05-11
- C#实现在线点餐系统 2023-02-03
- C#类的成员之Field字段的使用 2023-06-08
- C#实现文字视频生成器的示例代码 2023-07-05
- C#使用Log4.net记录日志文件 2023-05-31
- C#编写Windows服务程序详细步骤详解(图文) 2022-11-18
- C# 如何生成 DataMatrix 格式的二维码 2023-05-06