将类对象指针打包成 char * 用于消息队列
是否可以通过 POSIX 消息队列正确且安全地传递类对象指针?
例如,
Object *obj = new Object();
mq_send(mqdes, static_cast<char*>&obj, sizeof(obj), 1);
在接收端,执行 reinterpret_cast
返回到我的 Object
?
由于消息队列在 Linux 上使用文件描述符,我很好奇它是如何工作的。我尝试过但不成功,但我认为我可能做错了什么。
Is it possible to properly and safely pass a class object pointer through a POSIX message queue?
For instance,
Object *obj = new Object();
mq_send(mqdes, static_cast<char*>&obj, sizeof(obj), 1);
and on the receive side, perform a reinterpret_cast
back to my Object
?
Since message queues use a file descriptor on Linux, I am curious how this works. I have tried it unsuccessfully but think I may be doing something wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并非如此......仅当对象仅包含基本类型字段和具有基本类型字段的其他结构时。如果您发送一个指针,如果它驻留在另一个进程或另一个系统中,则不能从另一端重用它。
还使用带有继承和虚方法的类,可能会一团糟!
从我的角度来看,最好添加一种 Serialize 方法。
此外,以这种方式传递序列化的结构体二进制文件根本不可移植,并且如果您想在其他系统中使用相同的机制或者更改结构或对象打包等内容,可能会给您带来几个问题。
自定义序列化\反序列化将是首选并且更可移植,但选择当然是您的。
就像...
如果您只是在两个线程之间发送而不是发送对象的内容,我将只发送指向用 new 分配的对象的指针,然后我将从另一端取消分配它。
请注意,当您处置队列时,您必须首先销毁所有挂起的对象!
请注意 sizeof(Object*)...您只需发送指针,而不是对象本身。
Not really... only if the object contains only basic type fields and other structs with basic type fields. If you send a pointer it cannot be reused from the other side if it resides in another process or in another system.
Also using classes with inheritance and virtual methods, it may be a mess!
It is better to add a sort of Serialize method from my point of view.
Also passing a struct binary serialized in this way is not portable at all and can bring you to several problems if you want to use the same mechanism with other systems or if you change the structure or things like the packing of the object.
A custom serialization\deserialization would be preferred and more portable, but the choice is of course your.
Something like ...
If you are just sending between two threads instead of sending the content of the object i would send just the pointer to an object allocated with new and i would deallocate it from the other side.
Be careful that when you dispose the queue you must have first destroyed all pending objects!
Note the sizeof(Object*)... you need to send only the pointer, not the object itself.