StitchATon2/Infra/Buffers/UnmanagedMemory.cs

38 lines
No EOL
940 B
C#

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StitchATon2.Infra.Buffers;
/// <summary>
/// Provide non-thread safe anti GC contiguous memory.
/// </summary>
/// <typeparam name="T"></typeparam>
internal sealed unsafe class UnmanagedMemory<T> : IBuffer<T> where T : unmanaged
{
internal readonly T* Pointer;
private bool _disposed;
public int Length { get; }
public ref T this[int index] => ref Unsafe.AsRef<T>(Pointer + index);
public Span<T> Span => new(Pointer, Length);
public UnmanagedMemory(int length)
{
Pointer = (T*)NativeMemory.Alloc((nuint)length, (nuint)Unsafe.SizeOf<T>());
Length = length;
}
~UnmanagedMemory() => Dispose();
public void Dispose()
{
if (!_disposed)
{
NativeMemory.Free(Pointer);
GC.SuppressFinalize(this);
_disposed = true;
}
}
}