Sending a struct via QShareMemory
-
Hi! I have a struct:
struct control_data{
int column_number;
QString cell;
};
I need to send it from one thread to another.
Sending thread:
shmem.setKey("shmem");
if (shmem.isAttached()) shmem.detach();
if (!shmem.create(512)){
qDebug() << "error creating QSharedMemory segment";
if(shmem.error()) qDebug() << shmem.errorString();
}
....
QBuffer buffer;
buffer.open( QBuffer::ReadWrite );
QDataStream out( &buffer );
control_data data;
data.cell = "example";
data.column_number = 2;
out << data.cell;
out << data.column_number;
int size = buffer.size();
shmem.lock();
char *to = (char*)shmem.data();
const char *from = buffer.data().data();
memcpy(to, from,qMin( shmem.size(), size ));
shmem.unlock();
And recieving thread:
shmem.setKey("shmem");
....
control_data input;
QBuffer buffer;
buffer.open( QBuffer::ReadWrite );
QDataStream in( &buffer );
if (!shmem.attach()) {
qDebug() << "MainWindow: Unable to attach to shared memory segment";
return;
}
shmem.lock();
buffer.setData((char*)shmem.constData(), shmem.size());
buffer.open(QBuffer::ReadOnly);
in >> input.cell;
in >> input.column_number;
shmem.unlock();
shmem.detach();
qDebug() << input.cell;
qDebug() << input.column_number;
So in this example instead of reading from shared memory int 2 and string "example" i read zero and empty string. What am i doing wrong?
-
hi,
I suggest that send the data of structure, not string &int.control_data data;
data.cell = "example";
data.column_number = 2;
struct control_data *to = (control_data *)shmem.data();
struct control_data *from =data;
memcpy(to, from,sizeof(control_data));->like this...
-
SHM.setKey("TEST11");
SHM.attach();
SHM.create(sizeof(shm_BlockData));
SHM.lock();shm_BlockData *from=new shm_BlockData;
from->....;
from->...;
shm_BlockData to ;
*
to=(shm_BlockData)SHM.data();
memcpy(to,from,sizeof(shm_BlockData));sorry, i find the code in my project....
Maybe, the problem occured there ,
struct control_data *data; -> struct control_data *data= new control_data;
i miss allocate ...
sorry, i don't know byte array method.. another programmer will help you!
i use that(struct method) in my project. i hope to help you using my reply...:(