将对象(密封)的破坏与非托管缓冲区的破坏联系起来

发布于 2024-10-09 07:17:46 字数 385 浏览 8 评论 0原文

我首先解释一下我的情况:我有兴趣使用 位图构造函数scan0、步幅和格式,因为我正在解码平铺图像,并且我想选择自己的步幅,这样我就可以解码平铺图像,而无需关心解码器部分的边界。

无论如何,问题是文档说: 调用者负责分配和释放由scan0参数指定的内存块。但是,在相关的位图被释放之前,内存不应该被释放。

我不能轻易地释放缓冲区,因为位图随后被传递给另一个类,该类最终会销毁它,而我无法控制它。有没有某种方法(hacky,我知道)告诉 GC 在位图被销毁时也释放我的缓冲区?

(此外,欢迎任何替代解决方案)。

I'll explain my situation first: I'm interested of using the Bitmap constructor that takes scan0, stride and format, because I'm decoding tiled images and I'd like to choose my own stride so I can decode the tiles without caring about the bounds in the decoder part.

Anyway, the problem is that the documentation says:
The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory should not be released until the related Bitmap is released.

I can't release the buffer easily, because the Bitmap is then passed to another class that will eventually destroy it and I don't have control over it. Is there some way (hacky, I know) to tell the GC to also release my buffer when the Bitmap is destroyed?

(Also, any alternative solution is welcome).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彩扇题诗 2024-10-16 07:17:46

查看 ConditionalWeakTable。它是一个特殊的字典类,其中的键是弱引用的,并且只要键还活着,值就保持活动状态。

您可以实例化 ConditionalWeakTable其中 UnmanagedMemoryHandle 是一个自定义类,它包含指向非托管内存的指针,并在释放或最终确定该内存时释放该内存。位图将被表弱引用;只要 Bitmap 存在,UnmanagedMemoryHandle 就会保持活动状态,因此当 Bitmap 被垃圾收集时,非托管内存将被释放。

Have a look at the ConditionalWeakTable<TKey, TValue> Class. It's a special dictionary class where the keys are weakly referenced, and the values are kept alive as long as the key is alive.

You could instantiate a ConditionalWeakTable<Bitmap, UnmanagedMemoryHandle> where UnmanagedMemoryHandle is a custom class that contains the pointer to the unmanaged memory and releases that memory when it's disposed or finalised. The Bitmap would be weakly referenced by the table; UnmanagedMemoryHandle will be kept alive as long as the Bitmap lives, so the unmanaged memory will be freed when the Bitmap is garbage collected.

深者入戏 2024-10-16 07:17:46

如果一个类创建了一个非托管资源,那么不要让其他任何人销毁它,因为它会很混乱。仅在创建该资源的类中使用非托管资源。例如,您可以克隆位图并发布它。

If a class creates an unmanaged resource, then don't let anyone else destroy it, because it will be messy. Only use the unmanaged resource inside the class that creates it. You can clone the bitmap and publish that, for example.

雪化雨蝶 2024-10-16 07:17:46

不,你在这里迷路了。问题是,如果跟踪内存,你又回到了 C++ 时代,基本上你“失去了”内存责任。无法意识到内存何时被释放。

No, you are lost here. Problem is that you are back in the C++ times if keeping track of memory, and basically you "loose" the memory responsibility. No way to realize when the memoery is freed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文