Marshal.DestroyStructure与.Net中的Marshal.FreeHGlobal

Kei*_*ith 2 .net dispose unmanaged finalizer marshalling

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

我有一个顺序结构:

[StructLayout(LayoutKind.Sequential)]
struct FooBar { ... }
Run Code Online (Sandbox Code Playgroud)

然后在构造函数中我有:

// 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
Run Code Online (Sandbox Code Playgroud)

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

奖金问题:

  • 我的IDisposable类是否需要继承CriticalFinalizerObject以确保始终调用清理?
  • 有没有Microsoft.Win32.SafeHandles我可以用来包装危险的非托管内存的类?

xan*_*tos 7

都.在Marshal.DestroyStructure将释放的"内容" FooBar,同时Marshal.FreeHGlobal将释放的"容器".显然,首先你释放内容,然后释放容器.所以,第一Marshal.DestroyStructureMarshal.FreeHGlobal.

我不认为CriticalFinalizerObject与编组有任何关系struct,并且struct不能从任何东西继承,因此对第一个问题的反应是否定的.

  • @Keith Memory无法在进程死亡时泄露.分配的所有内存都由OS恢复.它就像操作系统处理内存的基石. (2认同)