Reading and writing to the buffer

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

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

  • How do I write safely to the buffer (ignoring the buffer overflow for now) ... I need to write in 32-bit chunks, since how do I change the position of the "write-pointer" between each 96-bit write? I am doing 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? **
    }
    
          

  • Is it safe for me to reserve memory, write multiple 96-bit objects, and then pass a pointer to the beginning of it to a second class (Reader) to ensure that both of them can access the same objects? (The reader will read the multiple of 96-bit objects at a time (~ 10,000), so I only need to know the beginning of the data to read.)

  • Once the reader has read the buffer, how do I "reset" the pointer (empty buffer) so I can write to the buffer again?

Buffer: A buffer is actually a pointer to the beginning of the memory area reserved posix_memalign

.

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

      

0


a source to share


3 answers


Just use pointer arithmetic, it will grow by the amount you want (by the size of the pointer 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.

      

+2


a source


Just increment the buffer pointer. This should work:



for(int count = 0; count < 100; ++count)  // for 100 96bit objects
{
    for(int32 i = 0; i < 3; ++i)
    {
        *buffer++ = *(myInt32 + i);
    }
}

      

+2


a source


Expanding on the idea of โ€‹โ€‹a spread pointer:

typedef struct {
    int a; int b; int c;
} myobj_t;

// allocate some memory
myobj_t *myobj_p, *myobj = malloc( ... );

myobj_p = myobj;  // don't want a memory leak
while ( ... ) {
myobj.a = x;
myobj.b = y;
myobj.c = z;

myobj++;
}

      

0


a source







All Articles