Search code examples
c#memory-mapped-files

MemoryMappedViewAccessor.ReadArray<> throws IndexOutOfRangeException


I'm trying to read a c-style unicode string from a memory-mapped file and IndexOutOfRangeException occurred, so I fixed it by copying char by char but I'd like to use ReadArray, which is more readable.

MemoryMappedFile file = MemoryMappedFile.OpenExisting("some name");
MemoryMappedViewAccessor view = file.CreateViewAccessor();
int len = (int)view.ReadUInt64(0); // Length of string + 1 is stored.
char[] buffer = new char[len];
//view.ReadArray<char>(0, buffer, sizeof(UInt64), len); // EXCEPTION
for (int i = 0; i < len; i++) // char by char, works fine.
    buffer[i] = view.ReadChar(sizeof(UInt64) + sizeof(char) * i);

Tried to find a short example showing how to use ReadArray<> but I couldn't.


Solution

  • in ReadArray, you indicate the desired position with the first parameter, and the offset within the array as the 3rd:

    public int ReadArray<T>(
        long position,
        T[] array,
        int offset,
        int count
    )
    

    So:

    view.ReadArray<char>(0, buffer, sizeof(UInt64), len);
    

    Is saying to fill the array at indexes from sizeof(UInt64) to sizeof(UInt64) + len - 1 - which will always overflow the usable index values (assuming sizeof(UInt64) is greater than 0 :-)).

    Try:

    view.ReadArray<char>(sizeof(UInt64), buffer, 0, len);