共享段初始化ID
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, sharedMemory("QSharedMemoryExample")
{
ui.setupUi(this);
connect(ui.loadFromFileButton, &QPushButton::clicked,
this, &Dialog::loadFromFile);
connect(ui.loadFromSharedMemoryButton, &QPushButton::clicked,
this, &Dialog::loadFromMemory);
setWindowTitle(tr("SharedMemory Example"));
}
加载内容并将内容上传到共享段中
void Dialog::loadFromFile()
{
if (sharedMemory.isAttached())
detach();
ui.label->setText(tr("Select an image file"));
QString fileName = QFileDialog::getOpenFileName(0, QString(), QString(),
tr("Images (*.png *.xpm *.jpg)"));
QImage image;
if (!image.load(fileName)) {
ui.label->setText(tr("Selected file is not an image, please select another."));
return;
}
ui.label->setPixmap(QPixmap::fromImage(image));
//! [1] //! [2]// load into shared memory
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << image;
int size = buffer.size();
if (!sharedMemory.create(size)) {
ui.label->setText(tr("Unable to create shared memory segment."));
return;
}
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemory.size(), size));
sharedMemory.unlock();
}
【qt|Qt_共享内存(QSharedMemory)未完成】从共享段中获取内容
void Dialog::loadFromMemory()
{
if (!sharedMemory.attach()) {
ui.label->setText(tr("Unable to attach to shared memory segment.\n" \
"Load an image first."));
return;
}QBuffer buffer;
QDataStream in(&buffer);
QImage image;
sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);
in >> image;
sharedMemory.unlock();
sharedMemory.detach();
ui.label->setPixmap(QPixmap::fromImage(image));
}
推荐阅读
- C++\QT|qt共享内存
- QT 组件化开发 自动生成基础组件
- C|【c ++ primer 笔记】第4章 表达式
- C|【c ++ primer 笔记】第3章 字符串、向量和数组
- 数据结构与算法(c++)|【18. 模拟栈和队列】
- C语言从0到1|【C语言】字符串函数
- cpp|cpp 模板函数,类模板(1)
- Java知识点|Java的@Aspect的@Around切不到Controller导致Controller中@Autowired的Service为空
- 初学至学会C++|初阶C++——C++第二节——类和对象(大全篇)