Jeffrey Goines
Jeffrey Goines

Reputation: 955

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.

Upvotes: 1

Views: 2000

Answers (2)

Jeffrey Goines
Jeffrey Goines

Reputation: 955

In ReadArray, Param 1 and 3 should be swapped.

Intellisense of VS 2010 incorrectly describes ReadArray<>'s parameters.

(may vary with language/locale of VS)

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239654

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);

Upvotes: 2

Related Questions