将 `fixed` 关键字与 `IntPtr.ToPointer` 一起使用

Using the `fixed` keyword with `IntPtr.ToPointer`

我正在编写图像处理方法,对不安全上下文中的固定指针有些困惑。通常我们使用 fixed 关键字和 addressof 运算符 &.

来固定指针
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 的影响?

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

LockBits()方法的调用是固定内存块的。这就是文档中提到方法时的意思:

Locks a Bitmap into system memory

稍后调用 UnlockBits() 取消固定(这就是为什么您应该将该调用放在 finally 块中)。