using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace NAPS2 { public abstract class UnmanagedBase : IDisposable { private bool disposed; ~UnmanagedBase() { Dispose(); } /// /// Gets the size of the unmanaged structure in bytes. If the structure is null, this is zero. /// public int Size { get; protected set; } /// /// Gets a value indicated whether the unmanaged structure is null. /// public bool IsNull { get { return Pointer == IntPtr.Zero; } } /// /// Gets a pointer to the unmanaged structure. If the provided value was null, this is IntPtr.Zero. /// public IntPtr Pointer { get; protected set; } /// /// Gets a managed copy of the unmanaged structure. /// public T Value { get { if (disposed) { throw new ObjectDisposedException("unmanaged"); } return GetValue(); } } public void Dispose() { if (Pointer != IntPtr.Zero && !disposed) { DestroyStructures(); Marshal.FreeHGlobal(Pointer); } disposed = true; } protected abstract T GetValue(); protected abstract void DestroyStructures(); public static implicit operator IntPtr(UnmanagedBase unmanaged) { return unmanaged.Pointer; } } }