如何让IntPtr访问MemoryMappedFile的视图?

时间:2015-07-02 08:15:12

标签: c# memory-mapped-files intptr

有没有办法直接IntPtr到MemoryMappedFile中的数据? 我有大数据块,频率变化很大,我不想复制它

1 个答案:

答案 0 :(得分:5)

不,不是IntPtr,无论如何都不会帮助你。您可以获得byte*,您可以随意转换它以访问实际的数据类型。如果必须,你可以把它投射到IntPtr。必须使用unsafe关键字是非常有意的。

创建MemoryMappedViewAccessor以在MMF上创建视图。然后使用其SafeMemoryMappedViewHandle属性的AcquirePointer()方法获取字节*。

演示用法并显示各种指针恶作剧的示例程序:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

class Program {
    static unsafe void Main(string[] args) {
        using (var mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew("test", 42))
        using (var view = mmf.CreateViewAccessor()) {
            byte* poke = null;
            view.SafeMemoryMappedViewHandle.AcquirePointer(ref poke);
            *(int*)poke = 0x12345678;
            Debug.Assert(*poke == 0x78);
            Debug.Assert(*(poke + 1) == 0x56);
            Debug.Assert(*(short*)poke == 0x5678);
            Debug.Assert(*((short*)poke + 1) == 0x1234);
            Debug.Assert(*(short*)(poke + 2) == 0x1234);
            IntPtr ipoke = (IntPtr)poke;
            Debug.Assert(Marshal.ReadInt32(ipoke) == 0x12345678);
            *(poke + 1) = 0xab;
            Debug.Assert(Marshal.ReadInt32(ipoke) == 0x1234ab78);
            view.SafeMemoryMappedViewHandle.ReleasePointer();
        }
    }
}