Qt中实现进程间通信的方法诸多,这里讲解比较简单的共享内存类QSharedMemory在这之前,先来看看这个类,其实函数不是很多,详细资料到官方文档查看
演示
![img](/uploads/images/file4_qt/qt0.gif)
下面代码注释写的比较清楚了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include<QDebug>
#define MEM_KEY "_sharedMemKey_" #include<QPixmap> #include<QBuffer> #define PIX_MAP "test.jpg" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); sharedMemory=new QSharedMemory(this); sharedMemory->setKey(MEM_KEY); } Widget::~Widget() { delete ui; }
void Widget::on_pushButton_clicked() { if(sharedMemory->isAttached()){ sharedMemory->detach(); } QPixmap pmp; pmp.load(PIX_MAP); ui->label->setPixmap(pmp.scaled(ui->label->size())); QBuffer tmpBuffer; tmpBuffer.open(QIODevice::ReadWrite); QDataStream dataOutstream(&tmpBuffer); dataOutstream<<pmp; int bufferSize=tmpBuffer.size(); if(sharedMemory->create(bufferSize)){ sharedMemory->lock(); const char *datasharedBuffer= tmpBuffer.data().data(); char *datasharedMemory=(char *)sharedMemory->data(); memcpy(datasharedMemory,datasharedBuffer,bufferSize); sharedMemory->unlock(); } tmpBuffer.close(); }
void Widget::on_pushButton_2_clicked() { if(sharedMemory->attach()){ qDebug()<<"ok!"; sharedMemory->lock(); QBuffer buffer; char *dataSharedMem=(char*)sharedMemory->data(); int dataSize =sharedMemory->size(); buffer.setData(QByteArray(dataSharedMem,dataSize)); QPixmap pmp; buffer.open(QIODevice::ReadOnly); QDataStream dataInStream(&buffer); dataInStream>>pmp; ui->label->setPixmap(pmp.scaled(ui->label->size())); sharedMemory->unlock(); if(sharedMemory->isAttached()){ sharedMemory->detach(); } buffer.close(); } }
|