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.
in
ReadArray, you indicate the desired position with the first parameter, and the offset within the array as the 3rd:So:
Is saying to fill the array at indexes from
sizeof(UInt64)tosizeof(UInt64) + len - 1– which will always overflow the usable index values (assumingsizeof(UInt64)is greater than 0 :-)).Try: