Important: Please read the Qt Code of Conduct -

Creating Reference Object to Shared Memory

  • I went through the official QT version of using Shared memory, which involves putting the data into a buffer and then putting that buffer data into the shared memory.

    Instead, could we create an object that is a pointer to sharedMemory.constData() so that whenever we change a assign a member of the object, it writes it to shared memory(I'll be using psuedocode so feel free to correct my syntax but the question is what I'm trying to achieve possible in QT):

    In the .h file:
    Class IPC {


    int x;
    int y;

    In the mainwindows.cpp file:

    //Our SharedMemory Object's name is sharedMemory

    if (!sharedMemory.create(size)) {
    ui.label->setText(tr("Unable to create shared memory segment."));
    //Instantiate the IPC class' ipcObject
    IPC *ipcObject = &sharedMemory.constData(since constData returns a pointer, not sure if we have to put bother the * and &)

    ipcObject.x = 4
    ipcObject.y = 5

    Basically, what I'm doing(trying to do) is create a pointer to the sharedMemory.constData(the data within the shared memory segment) and that pointer is an object(ipcObject). Then, rather than reference the sharedMemory object, I reference the ipcObject object and can access it's members(x and y) and can set variables and such and another QT program with the same class definition can access the same shared memory and access say ipcObject.x.

    The idea is instead of using memcpy and locking the shared memory everytime I want to copy something into the shared memory, I create an object that points to the address of the shared memory and can then set and access variables within the shared memory. I am aware that QT recommends you lock() the shared memory whenever you read from or write to it but is that required or just good safe form? I can see how it would be harmful to just leave a block of shared memory open(not locked) for a long period of time

    This is essentially (trying to) create a shared object(ipcObject) between two independent QT applications running on the same machine. Because the object points to the sharedMemory address, will this work?

  • This post is deleted!

  • sure you can do that, but you better use locking on writes, and conditionally on reads (such as if the reads are not atomic or access multiple elements in one operation). locks are not just good form. they are necessary when you have more than one task accessing the same memory concurrently.

    Also, you should probably use data() method instead.

    So yeah, you can put a wrapper around QSharedMemory that does locking...I would.

Log in to reply