class MyFileHandle : SafeHandle { public MyFileHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } } public static void Main(string[] args) { MyFileHandle fileHandle = NativeMethods.CreateFile("test.txt", ...); using (fileHandle) { // Do something with fileHandle } }
class MyMemoryHandle : SafeHandle { public MyMemoryHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } public static void Main(string[] args) { MyMemoryHandle memoryHandle = new MyMemoryHandle(); using (memoryHandle) { int size = 42; memoryHandle.SetHandle(Marshal.AllocHGlobal(size)); // Do something with memoryHandle } }In this example, we define a custom SafeHandle subclass `MyMemoryHandle` that wraps memory allocated with `malloc`. The `ReleaseHandle()` method calls `Marshal.FreeHGlobal` to release the memory. Package library: `System.Runtime.InteropServices` is part of the .NET Framework and is included in the `mscorlib` assembly.