qt 共享内存简单例子

进程1 初始化

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    if (NULL == m_pSharedMemory)
    {
        m_pSharedMemory = new QSharedMemory();
        QString qstrNativeKey = QString("ShareMemory");
        m_pSharedMemory->setNativeKey(qstrNativeKey);
    }
    // 判断该sm对象是否attch()该内存,是就解除
    if (m_pSharedMemory->isAttached())
    {
        m_pSharedMemory->detach();
    }
}

进程1 写数据

void MainWindow::on_pushButton_clicked()
{
    QString qstrId = ui->lineEdit->text();
    //写入共享内存数据
    //gbk编码
    QTextCodec* codeSource = QTextCodec::codecForName("GBK");
    QByteArray qa = codeSource->fromUnicode(qstrId);

    m_pSharedMemory->create(qstrId.toStdString().size());
    m_pSharedMemory->lock();
    char *to = (char*)m_pSharedMemory->data();
    memcpy(to ,qa.data() ,qa.size());
    m_pSharedMemory->unlock();
}

进程2 定时器轮询

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->m_timer = new QTimer(this);
    connect(m_timer,SIGNAL(timeout()),this, SLOT(slotScanningSharedMemory()));
    this->m_timer->start(1000);
}

进程2 轮询读取共享内存数据

void MainWindow::slotScanningSharedMemory()
{
    if (NULL == m_pSharedMemory)
    {
        m_pSharedMemory = new QSharedMemory();
        QString qstrNativeKey = QString("ShareMemory");
        m_pSharedMemory->setNativeKey(qstrNativeKey);
    }
    //先让sm对象attch()到共享内存
    if (!m_pSharedMemory->attach(QSharedMemory::ReadOnly))
    {
        //QMessageBox::information(this, "", "attach failed!");
        return;
    }

    //从共享内存中读取数据
    m_pSharedMemory->lock();
    QByteArray buffer;
    buffer.setRawData((char*)m_pSharedMemory->data(), m_pSharedMemory->size());

    //gbk编码
    QTextCodec* codeSource = QTextCodec::codecForName("GBK");
    QString qstrHouseId = codeSource->toUnicode(buffer.data());
    ui->lineEdit->setText("接收结果>>" + qstrHouseId);

    m_pSharedMemory->unlock();
    //解除attch
    m_pSharedMemory->detach();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值