質問

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.

役に立ちましたか?

解決

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 ...

template<typename T>
int SerializeAndSendObject(mqd_t mqdes, const T* instance)
{
    MySerializationStream stream;
    instance->SerializeTo(stream);
    mq_send(stream.toBuffer(), stream.size());
}

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!

Object* pointer = &obj;
mq_send(mqdes, static_cast<char*>(pointer), sizeof(Object*), 1);

Note the sizeof(Object*)... you need to send only the pointer, not the object itself.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top