// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
namespace Microsoft.Research.SEAL.Tools
{
///
/// Class that encapsulates the behavior of a class backed by a
/// pointer to a native object.
///
/// In particular, this class encapsulates the correct disposal
/// of the native pointer.
///
public abstract class NativeObject : DisposableObject
{
///
/// Construct a NativeObject instance
///
public NativeObject()
{
NativePtr = IntPtr.Zero;
owned_ = true;
}
///
/// Construct a NativeObject instance initializing it with a pointer
/// to a native object.
///
/// Pointer to native object.
/// Whether this instance owns the native pointer.
public NativeObject(IntPtr nativePtr, bool owned = true)
{
NativePtr = nativePtr;
owned_ = owned;
}
///
/// Descendants should call the appropriate method to
/// destroy the backing native object.
///
protected abstract void DestroyNativeObject();
///
/// Destroy native object if necessary
///
protected override void DisposeNativeResources()
{
base.DisposeNativeResources();
if (owned_ && !IntPtr.Zero.Equals(NativePtr))
{
DestroyNativeObject();
}
NativePtr = IntPtr.Zero;
}
///
/// Get/Set pointer to native object
///
internal IntPtr NativePtr
{
get
{
if (IsDisposed)
{
Type objType = this.GetType();
string objName = objType?.FullName ?? "Unknown object name";
throw new ObjectDisposedException(objName);
}
return nativePtr_;
}
set
{
nativePtr_ = value;
}
}
///
/// Whether this instance owns the native pointer.
///
private readonly bool owned_ = true;
///
/// Pointer to native object
///
private IntPtr nativePtr_ = IntPtr.Zero;
}
}