Does Bitmap.LockBits quot;pinquot; a bitmap into memory?(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 是否“固定"?位图进入内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Bitmap.LockBits 是否“固定"?位图进入内存?
基础教程推荐
- 创建属性设置器委托 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01