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 inheritCriticalFinalizerObject
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?
Both. The
Marshal.DestroyStructure
will free the "content" of theFooBar
, whileMarshal.FreeHGlobal
will free the "container". Clearly first you free the content, then the container. So firstMarshal.DestroyStructure
thenMarshal.FreeHGlobal
.I don't think
CriticalFinalizerObject
is in any way related to marshalingstruct
, and astruct
can't inherit from anything, so the response is no to the first question.