2 qq 37230349 qq_37230349 于 2017.09.12 15:53 提问

共享内存 读写数据 为什么不行 哪里错了吗。 20C
 #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."

2个回答

qq_37230349
qq_37230349   2017.09.12 15:57

是on_loadmemory_button_clicked() 的时候显示 Unable to attach to shared memory segment." 。

what237
what237   2017.11.16 15:57

你好,你的问题解决了吗,我也遇到这个问题。

Csdn user default icon
上传中...
上传图片
插入图片