Created
April 24, 2020 11:37
-
-
Save maloo/8b81e9844ba4270952b0f10212d838da to your computer and use it in GitHub Desktop.
MemoryMappedFile to Span sample
This file contains hidden or 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
using System; | |
using System.Buffers; | |
using System.IO.MemoryMappedFiles; | |
namespace VallmoVcdVisualizer.Services | |
{ | |
unsafe class MemoryMappedFileMemory : MemoryManager<byte> | |
{ | |
private readonly MemoryMappedFile mmf; | |
private readonly MemoryMappedViewAccessor ma; | |
private readonly byte* ptr; | |
public MemoryMappedFileMemory(string path) | |
{ | |
mmf = MemoryMappedFile.CreateFromFile(path); | |
ma = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); | |
ma.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr); | |
} | |
public ReadOnlySpan<byte> GetROSpan() => GetSpan(); | |
public override Span<byte> GetSpan() | |
{ | |
return new Span<byte>(ptr, (int)ma.Capacity); | |
} | |
public override MemoryHandle Pin(int elementIndex = 0) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override void Unpin() | |
{ | |
throw new NotImplementedException(); | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
ma.SafeMemoryMappedViewHandle.ReleasePointer(); | |
mmf.Dispose(); | |
ma.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment