C++ – Reading and writing to a buffer


I have 2 classes, one that writes multiple 96bit objects to a buffer (32bits at a time – 3x int32), and one that i want to read from the same buffer.

The first class (Writer) reserves and area of memory and creates a pointer to the first 32bit area.

  1. How do I write to the buffer safely (ignoring buffer overflow for now)… I need to write in 32bit chunks, so how do I change the position of the 'write pointer' between each 96bit write? Do I do something like:

    for(int count = 0; count < 100; ++count)  // for 100 96bit objects
        for(int32 i = 0; i < 3; ++i)
            *buffer = *(myInt32 + i);
        // ** how do I move the buffer ptr to the start of the next 96bit memory space? **
  2. Is it safe for me to reserve the memory, write a number of 96bit objects, then pass the pointer to the beginning of it to the second (Reader) class, to ensure they are both able to access the same objects? (The Reader will read multiples of 96bit objects in one go (~10,000), so I only need to know the start of the data for reading.)

  3. Once the Reader has read the buffer, how do I 'reset' the pointer (empty the buffer) so that I can write to the buffer again?

The buffer:
The buffer is actually a pointer to the beginning of an area of memory reserved by posix_memalign.

int32 *tempbufferPtr; 
posix_memalign ((void**)&tempbufferPtr, 8, 10000 ); // space for 10,000 objects 
writePtr = (my96bitObjectclass*)tempbufferPtr;

Best Solution

Just use pointer arithmetic, it will increase by the proper amount (by the size of the pointed-to object).

int32 *ptr = ...;

*ptr++ = 1;
*ptr++ = 2;
*ptr++ = 3;

// Here, ptr has been advanced by 3 times 32 bits, and is pointing at the next location.