Search code examples
c++qtqsharedmemory

Storing data in QSharedMemory


I'm trying to store four 'double' vars and an 'int' var in a shared memory.

QSharedMemory::data() offers a pointer to the memory that was set aside with create(int size). My question is: How can I appropriately join and deep copy that data onto the shared memory so I can access any of it's elements on another program for read/write?

The only similar thing I saw was by placing the values in a QString. Is that the right way?

Thanks.


Solution

  • Something along these lines:

    struct SharedData {
      double fourDoubles[4];
      int andAnInt;
    };
    
    QSharedMemory shared_mem;
    shared_mem.create(sizeof(SharedData));
    SharedData* p = static_cast<SharedData*>(shared_mem.data());
    p->fourDoubles[0] = 1.0;
    p->andAnInt = 42;