Files
whitemagic/WhiteMagic/Native/SafeMemoryHandle.cs
T
2026-07-21 22:30:10 +02:00

35 lines
1.0 KiB
C#

using Microsoft.Win32.SafeHandles;
namespace WhiteMagic.Native;
/// <summary>
/// A Win32 handle (process, thread, or snapshot) with a managed lifetime.
/// The handle closes with <c>CloseHandle</c>, even after an exception or a thread abort.
/// </summary>
/// <remarks>The pattern comes from MemorySharp's SafeMemoryHandle.</remarks>
public sealed class SafeMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Makes an empty handle. The interop marshaller uses this constructor for a
/// handle that a system call returns (for example, <see cref="NativeMethods.OpenProcess"/>).
/// </summary>
public SafeMemoryHandle() : base(true)
{
}
/// <summary>
/// Wraps a raw handle and takes ownership of the handle.
/// </summary>
/// <param name="handle">The handle to own.</param>
public SafeMemoryHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
/// <inheritdoc />
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(handle);
}
}