0

I have a struct

struct control_data{
    int column_number;
    QString cell;
};

I need to send it to another thread with the help of QShareMemory. I read that you can't do this because QString contains pointers inside. Any other ways?

r_spb
  • 75
  • 1
  • 14

1 Answers1

0

You have to serialize your struct to a Byte array. You can always convert your QString to a const char* like this:

myString.toStdString().c_str();

But serializing a QString should work.

  • The first step is to serialize your struct to a QDatastream using Qt, example here.

  • Then once your struct can be read and written you can pass it to a shared memory.

A complete example of using QSharedMemory can be found here.

Here is the relevant code:

// First, test whether a shared memory segment is already attached to the process.
// If so, detach it
if (sharedMem.isAttached())
{
    sharedMem.detach();
}

...

QBuffer buffer;
buffer.open( QBuffer::ReadWrite );
QDataStream out( &buffer );
out << youStruct;
int size = buffer.size();  // size of int + size of QString in bytes

if ( !sharedMem.create( size ) ) {
    return;
}

// Write into the shared memory
sharedMem.lock();
char *to = (char*)sharedMem.data();
const char *from = buffer.data().data();
memcpy( to, from, qMin( sharedMem.size(), size ) );
sharedMem.unlock();
Kirell
  • 9,228
  • 4
  • 46
  • 61
  • It is a byte array. Look closely, we copy the array with memcpy to another byte array belonging to the shared memory. You cannot serialize a pointer which points to a non-shared memory zone. – Kirell Jul 30 '15 at 08:53
  • So should i use const char* in a struct or i can leave qstring with qbuffer and qdatastream? – r_spb Jul 30 '15 at 09:15
  • Read my updated answer, it has everything to answer you problem. – Kirell Jul 30 '15 at 09:34