-1

I have used MapVirtualFile to map a file under Window using C++ VS2010. The void is

  void*                   m_pVoiceData;

I would now like to fill a structure with the data.

I have been using

void clsMapping::FeedPitchmarksFromMap(udtPitchmarks &uAudioInfo,unsigned long int uBytePos)
{

    unsigned long int iCountPM;
    memcpy(&iCountPM, &((char*)(m_pVoiceData))[uBytePos],sizeof(int));

    uAudioInfo.Pitchmarks.resize(iCountPM);

    for (unsigned long int i=0;i<iCountPM;i++)
    {
        iBytePos+=sizeof(int);
        unsigned long int iByteStart;
        memcpy(&iByteStart, &((char*)(m_pVoiceData))[iBytePos],4);

        iBytePos+=sizeof(int);
        unsigned long int iByteCount;
        memcpy(&iByteCount, &((char*)(m_pVoiceData))[iBytePos],4);

        iBytePos+=sizeof(int);
        unsigned int iF0;
        memcpy(&iF0, &((char*)(m_pVoiceData))[iBytePos],4);

        uAudioInfo.Pitchmarks[i].ByteStart =iByteStart;
        uAudioInfo.Pitchmarks[i].ByteCount =iByteCount;
        uAudioInfo.Pitchmarks[i].F0 =iF0;
    }
}

As one can see, I am currently using memcpy to get the data. Is there a faster way to do "get my data over"?

tmighty
  • 10,734
  • 21
  • 104
  • 218
  • You declare a `long` variable and copy `sizeof(int)` to it. Remember that `sizeof(long)` doesn't have to equal to `sizeof(int)`. – Some programmer dude Sep 14 '13 at 15:59
  • Also, is it really `iByteStart` as argument? Or is it `iBytePos` you mean? – Some programmer dude Sep 14 '13 at 16:06
  • Thank you. I mistyped it and edited my post now. And yep, I made a mistake assuming the size of int and long is the same. However, in my case it is, so no error (for now). I will change that. – tmighty Sep 14 '13 at 16:21

2 Answers2

2

Assuming that your memory-mapped file has exactly the same alignment and padding as the type of your uAudioInfo.Pitchmarks[0] (presumably a struct of some kind), you can just use one single memcpy to copy the whole lot, rather than memcpying individual fields like you're currently doing.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
2

The "fastest" would probably be simple assignment:

unsigned long iCountPM = 
    *reinterpret_cast<unsigned long*>(reinterpret_cast<char*>(m_pVoiceData) + uBytePos);

Can be used instead for all those memcpy calls in the function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • And that would be faster or just more elegant? – tmighty Sep 14 '13 at 16:14
  • @tmighty Well, both I would guess, as it's one function call and (possible) loop less. – Some programmer dude Sep 14 '13 at 20:12
  • 1
    I'm suggesting even further, that if the memory-mapped file is laid out exactly the same as an array of the structures in memory, _all_ elements of the array can be copied with a single `memcpy`. That's where it's even faster than "simple assignment". – C. K. Young Sep 14 '13 at 20:35