Created
September 3, 2022 14:45
-
-
Save StephenCleary/f1979af09cd02636e648b45f8a92fe5e to your computer and use it in GitHub Desktop.
IMemoryOwner for aligned memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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