Qt5,读写共享内存,Windows下同一个进程下可测试;
通过查看控制台输出即可看到写入和读出的内容;
相比网上其他介绍的方法,大部分均不支持汉字的正常读取,下面方法已经做了汉字存储的支持,可以进行测试;
cpp
#include <QSharedMemory> //头文件引入
#include <QDateTime>
//声明变量
QSharedMemory wrire_sharedMemory;
QSharedMemory read_sharedMemory;
写内存:
cpp
void MainWindow::writeShareMemory(const QString _key ,const QString _value){
qDebug() << __PRETTY_FUNCTION__ << ":_key" << _key << " ;_value:" << _value;
wrire_sharedMemory.setKey(_key);
if(wrire_sharedMemory.isAttached())
{
//将该进程与共享内存段分离
wrire_sharedMemory.detach();
}
if (!wrire_sharedMemory.create(1024)) {
qDebug() << __PRETTY_FUNCTION__ << "Cannot create shared memory.";
return ;
}
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << _value;
int size = buffer.size();
wrire_sharedMemory.lock();
char *to = (char*)wrire_sharedMemory.data();
const char *from = buffer.data().data();
memcpy(to,from, qMin(wrire_sharedMemory.size(), size));
wrire_sharedMemory.unlock();
}
读内存:
cpp
void MainWindow::readShareMemory(const QString _key ,QString &msg){
qDebug() << __PRETTY_FUNCTION__ << ":_key:" << _key;
read_sharedMemory.setKey(_key);
// 尝试附加到共享内存
if (!read_sharedMemory.attach(QSharedMemory::ReadOnly)) {
qDebug() << __PRETTY_FUNCTION__ << "无法附加到共享内存区域。";
return ;
}
QBuffer buffer;
QDataStream in(&buffer);
read_sharedMemory.lock();
buffer.setData((char*)read_sharedMemory.constData(), read_sharedMemory.size());
buffer.open(QBuffer::ReadOnly);
in >> msg;
qDebug() << __PRETTY_FUNCTION__ << " 方法内,从共享内存读取的数据:" << msg;
read_sharedMemory.unlock(); // 锁定共享内存
read_sharedMemory.detach();
}
测试代码:
下面方法通过添加按钮事件触发即可测试
cpp
//测试写
QDateTime currentTime = QDateTime::currentDateTime();
QString currentTimeString = currentTime.toString("测试代码,yyyy-MM-dd_hh:mm:ss");
writeShareMemory("key666" ,currentTimeString);
cpp
//测试读
QString msg = "";
readShareMemory("key666" ,msg);
qDebug() << "函数返回,从共享内存读取的数据msg:" << msg;