使用PositionPointer与MemoryMappedFile抛出异常?

时间:2019-12-08 12:28:18

标签: c# memory-mapped-files

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

  

其他信息:从SafeBuffer创建的UnmanagedMemoryStream不支持此操作。

,好的,不支持,但是为什么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;
        }

1 个答案:

答案 0 :(得分:1)

我也遇到了这个问题,我不确定为什么访问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 );