2015-07-10 58 views
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影响?

回答

1

这里你不需要fixed。这是幸运的,因为编译器不会让你使用它。 :)

LockBits()方法的调用是内存块的引脚。而这正是在文档中意味着当它说,该方法:

锁定一个位图到系统内存

稍后再打UnlockBits() unpins它(这就是为什么你应该把该呼叫在finally块) 。