Bitmap.LockBits 是否“固定"?位图进入内存?

时间:2022-11-23
本文介绍了Bitmap.LockBits 是否“固定"?位图进入内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近经常使用锁定位图,并且不断收到试图访问无效内存"错误.这主要是因为位图已在内存中移动.有些人使用 GCHandle.Alloc() 在 CLR 中分配内存并固定它.Bitmap.LockBits() 做同样的事情吗?我不明白锁定"内存和固定"内存之间的区别.您能否解释一下术语和差异(如果有)?

I'm using locked bitmaps a lot recently, and I keep getting "attempted to access invalid memory" errors. This is mostly because the bitmap has been moved in memory. Some people using GCHandle.Alloc() to allocate memory in the CLR and pin it. Does Bitmap.LockBits() do the same? I don't understand the difference between "locking" memory and "pinning" memory. Can you also explain the terminology and the differences if any?

推荐答案

GCHandle.Alloc 是一种更通用的方法,它允许您为任何托管对象分配一个句柄并将其固定在内存中(或不).固定内存可防止 GC 移动它,这在您必须将某些数据(例如数组)传递给非托管代码时特别有用.

GCHandle.Alloc is a more generic method, that allows you to allocate a handle to any managed object and pin it in memory (or not). Pinning memory prevents GC from moving it around, which is especially useful when you have to pass some data, for example an array, to a unmanaged code.

GCHandle.Alloc 不会以任何方式帮助您访问位图的数据,因为固定此对象只会阻止托管对象四处移动(位图对象)(并被垃圾收集).

GCHandle.Alloc will not help you access bitmap's data in any way, because pinning this object will just prevent the managed object from moving around (the Bitmap object) (and being garbage collected).

然而,位图是对原生 GDI+ 的 BITMAP 结构的包装.它不会将数据保存在您必须固定的任何托管数组中,它只是管理 GDI+ 位图对象的本机句柄.因为 Bitmap.LockBits 是一种告诉这个位图你有兴趣访问它的内存的方式,它只是一个关于 GdipBitmapLockBits 函数的包装器.因此,您需要调用它更多地与您使用 GDI+ 位图的事实有关,而不是与您在使用 GC 的托管环境中工作的事实有关.

Bitmap however is a wrapper around native GDI+'s BITMAP structure. It doesn't keep data in any managed array that you would have to pin, it just managed a native handle to GDI+ bitmap object. Because of that Bitmap.LockBits is a way of telling this bitmap that you are interested in accessing it's memory, and it's just a wrapper around GdipBitmapLockBits function. So your need of calling it has more to do with the fact that you are working with GDI+ bitmaps than with the fact, that you're working in managed environment with GC.

一旦您使用了LockBits,您应该能够通过BitmapData.Scan0 使用指针访问它的内存——它是数据第一个字节的地址.只要您不访问 BitmapData.Scan0 + Height * Stride 后面的内存,您就不应该有问题.

Once you have used LockBits you should be able to access it's memory using pointers through BitmapData.Scan0 - it's an address of first byte of data. You should not have problems as long, as you do not access memory behind BitmapData.Scan0 + Height * Stride.

完成后记得UnlockBits.

这篇关于Bitmap.LockBits 是否“固定"?位图进入内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:将现有图形转换为位图 下一篇:LockBits 图像旋转方法不起作用?

相关文章

最新文章