我是QT的新手。我已经看到 QT 为共享内存提供的基本示例,但我想使用共享内存共享结构。我怎样才能实现它?
void Dialog::Send()
{
if (sharedMemory.isAttached())
detach();
QBuffer buffer;
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << structa->a;
out << structa->b;
out << structa->c;
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(), buffersize));
sharedMemory.unlock();
}
在接收函数中,我在缓冲区中正确获取数据,但我无法将其转换为可验证的 Struct。
void Dialog::Receive()
{
if (!(sharedMemory.attach()))
{
ui.label->setText(tr("Unable to attach to shared memory segment.\n" \
"Load an image first."));
return;
}
QByteArray byteArray;
QBuffer buffer(&byteArray);
QDataStream in(&buffer);
TestStruct tmp; //Re-make the struct
sharedMemory.lock();
buffer.setData((char*)sharedMemory.constData(), sizeof(tmp));
buffer.open(QBuffer::ReadOnly);
int nSize = ((buffer.size()));
memcpy(&tmp, buffer.data().data(), nSize);
qDebug()<< " tmp.a = "<<tmp.a;
qDebug()<< " tmp.b = "<<tmp.b;
qDebug()<< " tmp.c = "<< tmp.c;
sharedMemory.unlock();
sharedMemory.detach();
}