Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Created September 3, 2022 14:45
Show Gist options
  • Save StephenCleary/f1979af09cd02636e648b45f8a92fe5e to your computer and use it in GitHub Desktop.
Save StephenCleary/f1979af09cd02636e648b45f8a92fe5e to your computer and use it in GitHub Desktop.
IMemoryOwner for aligned memory
public abstract class AlignedMemoryManager : MemoryManager<byte>
{
// Note: No finalizer; this will deliberately leak memory if never disposed.
// https://gist.github.com/GrabYourPitchforks/8efb15abbd90bc5b128f64981766e834#implementation-notes-when-subclassing-memorymanagert
private IntPtr _pointer;
protected static unsafe IntPtr Allocate(nuint byteCount, nuint alignment) => (IntPtr)NativeMemory.AlignedAlloc(byteCount, alignment);
public override unsafe Span<byte> GetSpan() => new((void*)_pointer, ByteCount);
public override unsafe MemoryHandle Pin(int elementIndex = 0) => new((byte*)_pointer + elementIndex);
public override void Unpin() { }
protected AlignedMemoryManager(IntPtr pointer) => _pointer = pointer;
protected abstract int ByteCount { get; }
protected override unsafe void Dispose(bool disposing)
{
var localHandle = Interlocked.Exchange(ref _pointer, IntPtr.Zero);
NativeMemory.AlignedFree((void*)localHandle);
}
}
public sealed class SystemPageSizeAlignedMemoryManager : AlignedMemoryManager
{
public IMemoryOwner<byte> Allocate() => new SystemPageSizeAlignedMemoryManager();
public SystemPageSizeAlignedMemoryManager()
: base(AlignedMemoryManager.Allocate((nuint)Environment.SystemPageSize, (nuint)Environment.SystemPageSize))
{
}
protected override int ByteCount => Environment.SystemPageSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment