将 PositionPointer 与 MemoryMappedFile 一起使用抛出异常?

using PositionPointer with MemoryMappedFile throw exception?

当我将 PositionPointer 与 MemoryMappedFile 一起使用时,出现错误

Additional information: This operation is not supported for an UnmanagedMemoryStream created from a SafeBuffer.

,好吧,它不受支持,但为什么 c# 开发人员将此 属性 放在 MemoryMappedViewStream

这是我的代码:

    FileStream fs = new FileStream("hello.txt", FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.ReadWrite);

        MemoryMappedFile mem = MemoryMappedFile.CreateFromFile(fs,"map",0,
MemoryMappedFileAccess.ReadWrite,null,0,false);


        MemoryMappedViewStream mems = mem.CreateViewStream(0, 0, MemoryMappedFileAccess.ReadWrite);

        unsafe
        {
            byte* pointer = mems.PositionPointer;
        }

我也 运行 遇到过这个问题,我不确定为什么访问 PositionPointer 会抛出 MemoryMappedViewStream 但如果你使用 MemoryMappedViewAccessor 而不是能够获得指针。

using var file = MemoryMappedFile.CreateNew( "MyCustomFile", 1024, MemoryMappedFileAccess.ReadWrite );
using var view = file.CreateViewAccessor( 0, 512, MemoryMappedFileAccess.ReadWrite );            

// Attain a pointer to the unmanaged memory.
byte* ptr = null;
view.SafeMemoryMappedViewHandle.AcquirePointer( ref ptr );

// You can store the pointer in a span for
// easy manipulation.
var span = new Span<byte>( ptr, 512 );