开发者

C++ (semi) Reflection for file save/load? (Hack?)

I have a bunch of structs in C++. I'd like to save it to file and load them up again. Problem is a few of my structs are pointers to base classes(/structs). So i'd need a way to figure out the type and create it. They really are just POD, they all have public members and no constructors.

What is the easiest way to save and 开发者_开发技巧load them from file? I have a LOT of structs and the only types i use are ints, pointers or c strings. I am thinking i could do some macro hacks. But really i have no idea what i should do.


Have you tried the Boost serialization library?


Don't roll your own here - use something well-developed and tested. One idea is Protocol Buffers


The pointers pose a specific issue: I suppose that multiple struct may actually refer to the same pointer and that you'd like a single pointer to be recreated when deserializing...

The first idea, to avoid boiler-plate code, is to create a compile-time reflexion tool:

  • BOOST_FUSION_ADAPT_STRUCT
  • BOOST_FUSION_ADAPT_STRUCT_NAMED

Those 2 macros will generate some wicked information on your struct so that you can then use them with Fusion algorithms, which cross the gap between compile-time and run-time.

Now, you need something that will be able to serialize and deserialize your data. Deserialization is usually a bit more difficult, though here you have the advantage of no polymorphism (which always makes things difficult).

Normally, on a first pass you identify the graph of objects to serialize, assign them all an ID, and use this ID in lieu of the pointer when serializing. For deserializing, you use a 3-columns map:

  • the map is ID -> (pointer to allocated object, list of pointers that could not be set)
  • allocate all objects, filling the ID map with a pointer to the allocated object each time
  • when you need to deserialize an ID, look it up in the map, if absent put a pointer to your pointer in the corresponding list
  • when you put the pointer to the allocated object in the map, take the time to fill all 'not set' pointers (and remove the list at the same time)

Of course, it's better to have frameworks handling it for you. You may try out s11n, if I remember correctly it handles cycles of references.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜