1
我正在编写图像处理方法,并对不安全上下文中的固定指针有些疑惑。通常我们使用fixed
关键字与addressof
运营商&
一起修复指针。在`IntPtr.ToPointer`中使用`fixed`关键字
fixed (int* p = &pt.x) // Common example does not seem to apply in my case.
当使用Bitmap.LockBits
介绍,我们通过BitmapData.Scan0
返回IntPtr
。
using (var bitmap = new Bitmap(800, 600))
{
var data = bitmap.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Error: You cannot use the fixed statement to take the address of an already fixed expression.
fixed (void* p = data.Scan0.ToPointer()) {...}
// Works fine but does [byte* p] remain fixed?
byte* p = (byte*) data.Scan0.ToPointer();
bitmap.UnlockBits(data);
}
问题是,我们需要在这种情况下使用fixed关键字吗?如果不是,byte* p
如何不受GC影响?