Marshal.DestroyStructure vs Marshal.FreeHGlobal in .Net

1.6k views Asked by At

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

I have a sequential struct:

[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

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?

Bonus questions:

  • 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?
1

There are 1 answers

8
xanatos On BEST ANSWER

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.

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.