本文介绍了.Net中的Marshal.DestroyStructure对比Marshal.FreeHGlobal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个托管.Net类,该类创建我需要确保正确清理的非托管资源.

I have a managed .Net class that creates unmanaged resources that I need to ensure are cleaned up properly.

我有一个顺序结构:

[StructLayout(LayoutKind.Sequential)]
struct FooBar { ... }

然后在构造函数中我拥有:

Then in the constructor I have:

// Allocate the memory
var fb = new FooBar(...);
int length = Marshal.SizeOf(typeof(FooBar));
this.pointer = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(fb, this.pointer, false);

// Then I use this.pointer in extern calls

然后在我的〜Finaliser / Dispose 方法中,我是否使用 Marshal.DestroyStructure Marshal.FreeHGlobal 或两者(如果是这样又以什么顺序)都可以忍受,我不会泄漏内存吗?

Then in my ~Finaliser/Dispose methods do I use Marshal.DestroyStructure or Marshal.FreeHGlobal or both (and if so in what order) to endure I don't leak the memory?

奖金问题:

  • 我的 IDisposable 类是否需要继承 CriticalFinalizerObject 以确保始终调用清除操作?
  • 是否可以在这里使用 Microsoft.Win32.SafeHandles 类包装危险的非托管内存?
  • Does my IDisposable class need to inherit CriticalFinalizerObject to ensure that the cleanup is always called?
  • Is there a Microsoft.Win32.SafeHandles class I could use here to wrap the dangerous unmanaged memory?

推荐答案

两者. Marshal.DestroyStructure 将释放 FooBar 的内容",而 Marshal.FreeHGlobal 将释放容器".显然,首先您要释放内容,然后是容器.因此,首先是 Marshal.DestroyStructure ,然后是 Marshal.FreeHGlobal .

Both. The Marshal.DestroyStructure will free the "content" of the FooBar, while Marshal.FreeHGlobal will free the "container". Clearly first you free the content, then the container. So first Marshal.DestroyStructure then Marshal.FreeHGlobal.

我不认为 CriticalFinalizerObject 与封送 struct 有任何关系,并且 struct 不能从任何东西继承,所以对第一个问题的回答是否".

I don't think CriticalFinalizerObject is in any way related to marshaling struct, and a struct can't inherit from anything, so the response is no to the first question.

这篇关于.Net中的Marshal.DestroyStructure对比Marshal.FreeHGlobal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 10:16