【Qt】Qt之进程间通信(共享内存)【转】
生活随笔
收集整理的這篇文章主要介紹了
【Qt】Qt之进程间通信(共享内存)【转】
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
簡述
上一節(jié)中,我們分享下如何利用Windows消息機(jī)制來進(jìn)行不同進(jìn)程間的通信。但是有很多局限性,比如:不能跨平臺,而且必須兩個進(jìn)程同時存在才可以,要么進(jìn)程A發(fā)了消息誰接收呢?
下面我們來分享另外一種跨平臺的進(jìn)行間通信的方式-Shared Memory(共享內(nèi)存)。
?
- 簡述
- 注意事項
- 加載進(jìn)內(nèi)存
- 說明
- 實現(xiàn)
- 從內(nèi)存中讀取
- 說明
- 實現(xiàn)
?
注意事項
初始化QSharedMemory時,必須指定一個唯一的標(biāo)識Key,進(jìn)程的Key必須保持一致。可以使用setKey來設(shè)置。
加載進(jìn)內(nèi)存
說明
進(jìn)程A-寫
分為下面幾步:
實現(xiàn)
void Dialog::loadFromFile() {if (sharedMemory.isAttached()){// 將該進(jìn)程與共享內(nèi)存段分離if (!sharedMemory.detach())qDebug() << "Unable to detach from shared memory."; } QString fileName = QFileDialog::getOpenFileName(0, QString(), QString(), tr("Images (*.png *.xpm *.jpg)")); QImage image; if (!image.load(fileName)) { qDebug() << "Selected file is not an image, please select another."; return; } // 將數(shù)據(jù)加載到共享內(nèi)存中 QBuffer buffer; buffer.open(QBuffer::ReadWrite); QDataStream out(&buffer); out << image; int size = buffer.size(); // 創(chuàng)建共享內(nèi)存段 if (!sharedMemory.create(size)) { qDebug() << sharedMemory.errorString() << "\n Unable to create shared memory segment."; return; } sharedMemory.lock(); char *to = (char*)sharedMemory.data(); const char *from = buffer.data().data(); memcpy(to, from, qMin(sharedMemory.size(), size)); sharedMemory.unlock(); }從內(nèi)存中讀取
說明
進(jìn)程B-讀
分為下面幾步:
實現(xiàn)
void MainWindow::loadFromMemory() {// 將共享內(nèi)存與該進(jìn)程綁定if (!sharedMemory.attach()) { qDebug() << "Unable to attach to shared memory segment."; return; } // 從共享內(nèi)存中讀取數(shù)據(jù) QBuffer buffer; QDataStream in(&buffer); QImage image; sharedMemory.lock(); buffer.setData((char*)sharedMemory.constData(), sharedMemory.size()); buffer.open(QBuffer::ReadOnly); in >> image; sharedMemory.unlock(); sharedMemory.detach(); m_pLabel->setPixmap(QPixmap::fromImage(image)); }原文作者:一去丶二三里
作者博客:去作者博客空間
轉(zhuǎn)載于:https://www.cnblogs.com/mzy-google/p/5165147.html
總結(jié)
以上是生活随笔為你收集整理的【Qt】Qt之进程间通信(共享内存)【转】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深信服桌面云-(1)
- 下一篇: 《FLUENT 14流场分析自学手册》—