Search code examples
c++arrayswindowsmemory-mapped-files

Copying part of an array stored in a memory mapped file


I have an array of doubles stored in a memory mapped file, and I want to read the last 3 entries of the array (or some arbitrary entry for that matter).

It is possible to copy the entire array stored in the MMF to an auxiliary array:

void ReadDataArrayToMMF(double* dataArray, int arrayLength, LPCTSTR* pBufPTR)
{
    CopyMemory(dataArray, (PVOID)*pBufPTR, sizeof(double)*arrayLength);
}

and use the needed entries, but that would mean copying the entire array for just a few values actually needed.

I can shrink arrayLength to some number n in order to get the first n entries, but I'm having problems with copying a part of the array that doesn't start from the first entry. I tried playing with pBufPTR pointer but could only get runtime errors.

Any ideas on how to access/copy memory from the middle of the array without needing to copy the entire array?


Solution

  • To find start offset for nth-element:

    const double *offset = reinterpret_cast<const double*>( *pBufPTR ) + n;
    

    To copy last 3 elements:

    CopyMemory( dataArray, reinterpret_cast<const double*>( *pBufPTR ) + arrayLength - 3, 3 * sizeof(double) );