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
IDisposableclass need to inheritCriticalFinalizerObjectto ensure that the cleanup is always called? - Is there a
Microsoft.Win32.SafeHandlesclass I could use here to wrap the dangerous unmanaged memory?
Both. The
Marshal.DestroyStructurewill free the "content" of theFooBar, whileMarshal.FreeHGlobalwill free the "container". Clearly first you free the content, then the container. So firstMarshal.DestroyStructurethenMarshal.FreeHGlobal.I don't think
CriticalFinalizerObjectis in any way related to marshalingstruct, and astructcan't inherit from anything, so the response is no to the first question.