-->

Passing non PODs [ Plain old DataTypes ] over IPC

2019-09-16 19:19发布

问题:

I am writing an implementation for doing IPC. User do a call, I take all these parameters and pass them onto other process.

I have written an automatic code generator for such functions based on logic which works something like this :

  1. Take all the parameters and put them inside a structure.
  2. Add other information required for IPC. Pass the size and pointer of this struct to POSIX message queue. Data from this address, till the size specified, is read and send to other process.
  3. De-construct the struct to get parameters.
  4. Call the actual function with these parameters.

This works perfectly fine when I have only Plain old Data types. But when the function parameters are non-PODs, my logic fails because :

  1. I cant really tell the size of total data in case of non-POD type [Required by message queues]
  2. Some classes might contain dynamically increasing entities like vectors.

Can someone give an idea how I might approach for this situation?

回答1:

You need to decide how to do serialization.

E.g. you could define a type which represents a message which is exchanged between parties, and then implement a generic function which serializes objects into message. When you have custom logic, you specialize the serialization function.

here's some pseudocode:

class Message {...} // blah blah

// default imple
template<typename T>
Message& operator <<(Message& msg, T& t) { .. write it as a POD .. }

// specialize for types which need custom logic
Message& operator <<(Message& msg, SomeCustomType& x) { .. custom serialization ..}

To deserialize you need to do similar for operator >>. Then you do:

Message msg;
MyType whatever = ...
msg << whatever;
// now send msg to other side.

Of course you will need some metadata in message so you know how to unpack on the other side (i.e. to which type).

There are plenty of examples (e.g. STL streams or how MFC abstracts it with CArchive class and Serialize method on serializable types)