【问题标题】:Using the `fixed` keyword with `IntPtr.ToPointer`将 `fixed` 关键字与 `IntPtr.ToPointer` 一起使用
【发布时间】:2015-07-10 00:32:31
【问题描述】:

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

fixed (int* p = &pt.x) // Common example does not seem to apply in my case.

当使用Bitmap.LockBits 时,我们得到一个IntPtr,由BitmapData.Scan0 返回。

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);
}

问题是,我们需要在这种情况下使用固定关键字吗?如果没有,byte* p 怎么不会受到 GC 的影响?

【问题讨论】:

    标签: c# .net pointers garbage-collection keyword


    【解决方案1】:

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

    LockBits() 方法的调用是固定内存块的方法。这就是文档中说该方法时的含义:

    将位图锁定到系统内存中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 2011-07-21
      • 1970-01-01
      • 2017-06-17
      相关资源
      最近更新 更多