我最近通过文章image processing in C#使不安全的代码在C#安全
阅读有一个在那里,我真的不喜欢,因为它是不安全的,我想一些代码知道它是否能进行安全:
public static bool Invert(Bitmap b)
{
// GDI+ still lies to us - the return format is BGR, NOT RGB.
BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
unsafe
{
byte * p = (byte *)(void *)Scan0;
int nOffset = stride - b.Width*3;
int nWidth = b.Width * 3;
for(int y=0;y < b.Height;++y)
{
for(int x=0; x < nWidth; ++x)
{
p[0] = (byte)(255-p[0]);
++p;
}
p += nOffset;
}
}
b.UnlockBits(bmData);
return true;
}
行byte* p = (byte*)(void*)Scan0;
模样的罪魁祸首,但我不得不说,我真的不明白它在做什么,或者它如何可以作出安全。
任何人都可以对此有所了解吗?
如果你不知道它在做什么,为什么你想“让它安全”?你害怕“不安全”这个词吗?该代码用于使用指针直接访问内存中的位图像素。另一种方法是使用GetPixel()来编组每个像素的数据,速度非常慢。 – CodeCaster
'Scan0'是一个'IntPtr',所以如果你想获得相同的处理速度,你基本上必须使用指针。 –
“我怎样才能让它不安全?” - 停止使用指针。如果你不知道_why_它的使用标记,那么就不要惹它(或找到某人知道它在做什么和_why_)。 –