using System;
using System.Runtime.InteropServices;
namespace Unity.Media
{
///
/// A class that handles the allocation and disposal of an object. All the different encoders use it.
///
/// The type of object that the handle refers to.
public class RefHandle : IDisposable
where T : class
{
///
/// Specifies whether the handle has been allocated or not.
///
public bool IsCreated { get { return m_Handle.IsAllocated; } }
///
/// The target object of the handle.
///
public T Target
{
get
{
if (!IsCreated)
return null;
return m_Handle.Target as T;
}
set
{
if (IsCreated)
m_Handle.Free();
if (value != null)
m_Handle = GCHandle.Alloc(value, GCHandleType.Normal);
}
}
GCHandle m_Handle;
private bool Disposed = false;
///
/// The constructor of the handle.
///
public RefHandle()
{
}
///
/// The constructor of the handle.
///
/// The object to use as the target of the handle.
public RefHandle(T target)
{
m_Handle = new GCHandle();
Target = target;
}
///
/// Cleans up the handle's resources.
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Cleans up the handle's resources.
///
/// If this is True, the method has been called by a user's code. Otherwise, it
/// has been called by the runtime and only unmanaged resources can be disposed.
public void Dispose(bool disposing)
{
if (Disposed)
return;
if (disposing)
{
// Free any other managed objects here.
}
// Free any unmanaged objects here.
if (IsCreated)
m_Handle.Free();
Disposed = true;
}
///
/// The finalizer of the class.
///
~RefHandle()
{
Dispose(false);
}
}
}