当前位置: 动力学知识库 > 问答 > 编程问答 >

Python-style pickling for C++?

问题描述:

Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because they're not serializable, or else because I just don't care to save them for later). This could be accomplished with an extra action at parse time, that would generate code to handle the automatic serialization. Has anyone heard of anything like that?

网友答案:

I don't believe there's any way to do this in a language with no run-time introspection capabilities.

网友答案:

perhaps xml Data Binding? gsoap is just one of many options. You can automatically generate code for mapping between data structure and xml schema. Not sure that setting this up would be easier than other options you mention

网友答案:

something that could automatically serialize all the members of a class

This is not possible in C++. Python, C#, Java et al. use run-time introspection to achieve this. You can't do that in C++, RTTI is not powerful enough.

In essence, there is nothing in the C++ language that would enable someone to discover the member variables of an object at run-time. Without that, you can't automatically serialize them.

网友答案:

There's the standard C++ serialization with the << and >> operators, although you'll have to implement these for each of your classes (which it sounds like you don't want to do). Some practitioners say you should alway implement these operators, although of course, most of us rarely do.

网友答案:

One quick way to do this that I got working once when I needed to save a struct to a file was to cast my struct to a char array and write it out to a file. Then when I wanted to load my struct back in, I would read the entire file (in binary mode), and cast the whole thing to my struct's type. Easy enough and exploits the fact that structs are stored as a contiguous block in memory. I wouldn't expect this to work with convoluted data structures or pointers, though, but food for thought.

分享给朋友:
您可能感兴趣的文章:
随机阅读: