StitchATon2/Infra/Buffers/UnmanagedMemory.cs

40 lines
1 KiB
C#
Raw Permalink Normal View History

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