Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How serialize a boost::function to send it in a message_queue

I am actually trying to serialize a boost::function using boost::serialize because I want to share it in a boost::interprocess::message_queue. I only see one way to do that, it is to use the non-intrusive version of boost::serialize.

namespace boost {   
 namespace serialization {
       template<class Archive>   
           void serialize(Archive & ar, boost::function<void()> & fct, const unsigned int version) 
       {
     ar & fct.args;
     ar & fct.arity;
     ar & fct.vtable;
     ar & fct.functor;
       }       
  }
}

I will also need to serialize vtable and functor, I didn't try it, I am not sure it is working.

So is there any way to serialize a boost::function in a proper way?

Thank you.

like image 434
Maxence SCHMITT Avatar asked Dec 15 '10 10:12

Maxence SCHMITT


2 Answers

It's not going to be possible immediately.

There are 2 problems I can think of:

  • pass the identity of the function
  • pass the context of the function (for example, if created using bind or with a lambda)

Neither is trivial, and neither can be done without instrumenting the code (think reflection / introspection).

What you want here is the Command pattern, and a way to serialize those commands.

This requires that both processes are built on top of a common set of commands (a common library seems like a good idea) and that you implement serialization and deserialization for your commands.

For deserialization, you will want to look-up the Virtual Constructor Idiom.

like image 149
Matthieu M. Avatar answered Nov 17 '22 01:11

Matthieu M.


I don't think there is any way to do it. To be able to serialize a function you would need to be able to serialize its binary code. But that is not possible as the code is at least platform dependent.

You may however make a function table and serialize index of a function in that table. In the deserializer you would need to construct that very same table and use the serialized index to get the real function from the table.

like image 2
Juraj Blaho Avatar answered Nov 17 '22 01:11

Juraj Blaho