【发布时间】: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