public void Dispose() { if (!UnsafeUtility.IsValidAllocator(m_AllocatorLabel)) { throw new InvalidOperationException("The NativeHeap can not be Disposed because it was not allocated with a valid allocator."); } DisposeSentinel.Dispose(ref m_Safety, ref m_DisposeSentinel); UnsafeUtility.Free(m_HeapData->mBuffer, m_AllocatorLabel); UnsafeUtility.Free(m_HeapData, m_AllocatorLabel); m_HeapData->capacity = 0; m_HeapData->m_length = 0; m_HeapData->mBuffer = null; m_HeapData = null; }
/// <summary> /// 构造函数 /// </summary> /// <param name="array"></param> /// <param name="allocator"></param> public NativeHeap(T[] array, Allocator allocator, bool isSmaller) { if (array == null) { throw new ArgumentNullException(nameof(array)); } m_HeapData = (NativeHeapData *)UnsafeUtility.Malloc(UnsafeUtility.SizeOf <NativeHeapData>(), UnsafeUtility.AlignOf <NativeHeapData>(), allocator); m_AllocatorLabel = allocator; //_compareFuc = compareFunc; this.isSmaller = isSmaller; var totalSize = UnsafeUtility.SizeOf <T>() * (long)array.Length; m_HeapData->mBuffer = UnsafeUtility.Malloc(totalSize, UnsafeUtility.AlignOf <T>(), allocator); m_HeapData->m_length = array.Length; m_HeapData->capacity = array.Length; DisposeSentinel.Create(out m_Safety, out m_DisposeSentinel, 1, allocator); Copy(array, this); for (int i = m_HeapData->m_length - 1 / 2; i >= 0; i--) { Heapify(i); } }
//public delegate bool Compare(T a, T b); //public Compare _compareFuc; /// <summary> /// 构造堆 /// </summary> /// <param name="array"></param> /// <param name="allocator"></param> public NativeHeap(int capacity, Allocator allocator, bool isSmaller) { if (allocator <= Allocator.None) { throw new ArgumentException("Allocator must be Temp, TempJob or Persistent", nameof(allocator)); } if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), "capacity must be>=0"); } m_HeapData = (NativeHeapData *)UnsafeUtility.Malloc(UnsafeUtility.SizeOf <NativeHeapData>(), UnsafeUtility.AlignOf <NativeHeapData>(), allocator); m_AllocatorLabel = allocator; //_compareFuc = compareFunc; this.isSmaller = isSmaller; capacity = Math.Max(1, capacity); var totalSize = UnsafeUtility.SizeOf <T>() * capacity; m_HeapData->mBuffer = UnsafeUtility.Malloc(totalSize, UnsafeUtility.AlignOf <T>(), allocator); m_HeapData->m_length = 0; m_HeapData->capacity = capacity; //用于检测内存泄漏,创建一个标志 DisposeSentinel.Create(out m_Safety, out m_DisposeSentinel, 1, allocator); }