qq_37230349
球磨川禊
2017-09-12 07:53

共享内存 读写数据 为什么不行 哪里错了吗。

20
  • qt
  • qt5 代码
  • 界面
 #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

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

    memory = new QSharedMemory("123");

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_loadfile_button_clicked()
{
    //先判断是否 存在共享内存
    if(this->memory->isAttached() ) //如果被连接 返回1
    {

       // this->memory->detach(); //断开连接

        if (!memory->detach())
                   qDebug() << "Unable to detach from shared memory.";

    }

    QString filename = QFileDialog::getOpenFileName(this,"选择",QString()
                                                    , tr("Images (*.png *.xpm *.jpg)") );
    QImage image;
    if( ! image.load(filename)  )
    {
        // 加载失败
        QMessageBox::information(this,"123","123");
        return ;
    }

    QBuffer buffer ;//QBuffer是 一个文件读写界面
    bool ok = buffer.open( QIODevice::ReadWrite );

    if(ok )
    {
        QDataStream Out(&buffer);
      //  QDataStream Out;Out.setDevice(&buffer);
        Out << image;

    }
    else
    {
        QMessageBox::information(this,"123","124");
    }

    int size = buffer.size();

    if(! memory->create(size) )
    {
        qDebug()<<memory->errorString()<<"can't create \n";
        return ;
    }

    memory->lock();

    char * to = (char *)memory->data();
    const char * from = buffer.data().data();
    memcpy(to,from, qMin(memory->size(),size) );

    memory->unlock();


}

void MainWindow::on_loadmemory_button_clicked()
{

    // 将共享内存与该进程绑定
    if (!memory->attach())
    {
        qDebug() << "Unable to attach to shared memory segment.";
        return;
    }

    QBuffer buffer;
    QDataStream in(&buffer);
    QImage image;

    memory->lock();

    buffer.setData( (char*)memory->constData(),memory->size()  );
    buffer.open( QIODevice::ReadWrite );

    in>> image;

    memory->unlock();
    memory->detach();
    pixmap = QPixmap::fromImage( image );
    ui->show_label->setPixmap( pixmap );


}

几乎就是帮助上的代码 选择图片什么的都可以
但是load的时候 就显示 "Unable to attach to shared memory segment."

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐

换一换