I'm using mqueue to communicate between threads and I'm having a problem passing objects.
The mq_send
and mq_receive
take a char*
as a parameter for the object.
I use them the following way.
foo* foo = new foo();
foo->set_id(3);
mq_send(myQueue, (char*)foo, 1024, 1);
then
char* buffer;
while(true)
{
ssize_t bytes_read;
bytes_read = mq_receive(myQueue, buffer, 1024, NULL);
foo* foo = (foo*) buffer;
foo->get_id(); //equals 3
//Send the object to another queue
mq_send(myOtherQueue, buffer, 1024, 1);
}
So far so good.
The problem is here
char* buffer;
while(true)
{
ssize_t bytes_read;
bytes_read = mq_receive(myOtherQueue, buffer, 1024, NULL);
foo* foo = (foo*) buffer;
foo->get_id(); //equals garbage 323234234
}
The second time I cast the buffer, I get garbage.
I read about static_cast
and dynamic_cast
and I can't find what's the problem.
What is wrong?
I see two issues here. First, is your Foo TriviallyCopyable
?
Second,
char* buffer;
bytes_read = mq_receive(myOtherQueue, buffer, 1024, NULL);
I do not see any allocation for buffer
.