球磨川禊 2017-09-12 07:53 采纳率: 0%
浏览 1974
已结题

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

 #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条回答 默认 最新

  • 球磨川禊 2017-09-12 07:57
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题