gpt4 book ai didi

c++ - QT如何读写共享内存创建数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:01 28 4
gpt4 key购买 nike

我尝试了以下方法:

int a[5]={1,2,3,4,5};
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << a[5];
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();

阅读

sharedMemory.attach();
QBuffer buffer;
QDataStream in(&buffer);
int a[5];
//QImage image;
QString fileName;
int num;
sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);
in >> a[5];
sharedMemory.unlock();

但是我想的方式不对,不知道读写的是字符数组和整数。

最佳答案

这里第一个真正的问题是 a[5]:数组 a 只有 5 个项目,所以第 5 个索引超出了它的范围。要写入和读取整个数组,您可以 1) 一次执行一项;或 2) 使用 vector 或列表对象,例如 QVector

<强>1。作为数组

写:

int a[5]={1,2,3,4,5};

QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);

//write item by item
for (int i=0; i<5; i++) {
out << a[i];
}

int size = buffer.size();
if (!sharedMemory.create(size)) {
cout << "Unable to create shared memory segment: "<<sharedMemory.errorString().toStdString()<<endl;
return;
}
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemory.size(), size));
sharedMemory.unlock();

阅读:

sharedMemory.attach();
QBuffer buffer;
QDataStream in(&buffer);

sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);

int len = sharedMemory.size()/sizeof(int);
int* a = new int[len];
for (int i=0; i< len; i++) {
in >> a[i];
}
sharedMemory.unlock();
//delete a;

(注意:不要忘记在使用后删除a。)

<强>2。作为 QVector

写:

QVector<int> vec;
vec << 1<<2<<3<<4<<5;

QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);

//write the vector object
out << vec;

int size = buffer.size();
if (!sharedMemory.create(size)) {
cout << "Unable to create shared memory segment: "<<sharedMemory.errorString().toStdString()<<endl;
return;
}
sharedMemory.lock();
char *to = (char*)sharedMemory.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemory.size(), size));
sharedMemory.unlock();

阅读:

sharedMemory.attach();
QBuffer buffer;
QDataStream in(&buffer);

sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
buffer.open(QBuffer::ReadOnly);

QVector<int> vec;
in>>vec;
sharedMemory.unlock();

关于c++ - QT如何读写共享内存创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31039887/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com