我正在使用mqueue在线程之间进行通信,但在传递对象时遇到问题。
mq_send
并将mq_receive
achar*
作为对象的参数。
我通过以下方式使用它们。
foo* foo = new foo();
foo->set_id(3);
mq_send(myQueue, (char*)foo, 1024, 1);
然后
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);
}
到现在为止还挺好。
问题就在这里
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
}
我第二次施放缓冲区时,我得到了垃圾。我读到了static_cast
,dynamic_cast
但我找不到问题所在。
怎么了?