PDA

View Full Version : Share multiple segment with QSharedMemory



boumacmilan
21st January 2014, 14:19
Hi every body

i want to use QSharedMemory to share data between 2 applications using it for sharing one segment works perfectly but when i try 2 share more than one i have access just to the last one

this my code

sharedMemroy.cpp in the first application




void SharedMemory::loadIntoSharedMem(QString memoryKey,QString &data)
{
sharedMem.setKey(memoryKey);
if (sharedMem.isAttached())
{
sharedMem.detach();
}
if( data.length())
{
// load into shared memory
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << data;
int size = buffer.size();

if (!sharedMem.create(size)) {
qDebug()<<"Unable to create shared memory segment."<<sharedMem.isAttached()<<" "<<sharedMem.error();

}

sharedMem.lock();
char *to = (char*)sharedMem.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMem.size(), size));
sharedMem.unlock();
}
else
{
qDebug()<< "no data to share"
}

}


and i main



SharedMemory sh;
sh.loadIntoSharedMem("memo1",data1 );
sh.loadIntoSharedMem("memo2",data2 );
sh.loadIntoSharedMem("memo3",data3 );



and on showSharedData.cpp in the seconde application




QString ShowSharedMemory::loadFromSharedMem(QString memoryKey)
{
sharedMem.setKey(memoryKey);
if (!sharedMem.attach())
{
qDebug()<<"Unable to load!";
return"";
}

QBuffer buffer;
QDataStream in(&buffer);
QString text;

sharedMem.lock();
buffer.setData((char*)sharedMem.constData(), sharedMem.size());
buffer.open(QBuffer::ReadOnly);
in >> text;
sharedMem.unlock();

sharedMem.detach();
return text;

}



and in main



data1=showMemory.loadFromSharedMem("memo1");
data2=showMemory.loadFromSharedMem("memo2");
data3=showMemory.loadFromSharedMem("memo3");



thanks for your help

boumacmilan
25th January 2014, 00:01
i resolve it by mading 3 object SharedMemory, i know its not a good methode , :o but it works :D
(sorry for my bad english)

anda_skoa
25th January 2014, 12:14
i resolve it by mading 3 object SharedMemory, i know its not a good methode

I don't think there is an alternative, so it is the right way to do it.

QSharedMemory is a bit like a smart pointer, so you need to keep it around as long as you want to work with the shared memory it is associated with.

Cheers,
_