How can I quickly read bytes from a memory mapped file in .NET?

后端 未结 4 1472
日久生厌
日久生厌 2020-12-13 20:01

In some situations the MemoryMappedViewAccessor class just doesn\'t cut it for reading bytes efficiently; the best we get is the generic ReadArray

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 20:30

    This solution requires unsafe code (compile with /unsafe switch), but grabs a pointer to the memory directly; then Marshal.Copy can be used. This is much, much faster than the methods provided by the .NET framework.

        // assumes part of a class where _view is a MemoryMappedViewAccessor object
    
        public unsafe byte[] ReadBytes(int offset, int num)
        {
            byte[] arr = new byte[num];
            byte *ptr = (byte*)0;
            this._view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
            Marshal.Copy(IntPtr.Add(new IntPtr(ptr), offset), arr, 0, num);
            this._view.SafeMemoryMappedViewHandle.ReleasePointer();
            return arr;
        }
    
        public unsafe void WriteBytes(int offset, byte[] data)
        {
            byte* ptr = (byte*)0;
            this._view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
            Marshal.Copy(data, 0, IntPtr.Add(new IntPtr(ptr), offset), data.Length);
            this._view.SafeMemoryMappedViewHandle.ReleasePointer();
        }
    

提交回复
热议问题