C++中的对象序列化 [英] Object serialization in C++
问题描述
我想序列化/反序列化一些结构化数据,以便通过char*缓冲区
通过网络发送.
I would like to serialize/deserialize some structured data in order to send it over the network via a char* buffer
.
更准确地说,假设我有一个 struct Message
类型的消息.
More precisely, suppose I have a message of type struct Message
.
struct Message {
Header header;
Address address;
size_t size; // size of data part
char* data;
} message
在 C 中,我会使用诸如:
In C, I would use something such as:
size = sizeof(Header) + sizeof(Address) + sizeof(size_t) + message.size;
memcpy(buffer, (char *) message, size);
序列化,和
Message m = (Message) buffer;
反序列化.
在 C++ 中执行此操作的正确"方法是什么.定义一个类而不是一个结构更好吗?我应该重载一些运算符吗?是否需要考虑对齐问题?
What would be the "right" way to do it in C++. Is it better to define a class rather than a struct. Should I overload some operators? are there alignment issues to consider?
感谢您指出char *"问题.提供的 C 版本不正确.data
字段指向的数据部分应该单独复制.
thanks for pointing the "char *" problem. The provided C version is incorrect. The data section pointed to by the data
field should be copied separately.
推荐答案
其实有很多种:
你可以提升让它为你做:http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/tutorial.html
You can boost let it do for you: http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/tutorial.html
重载流操作符<<
用于序列化和>>
用于反序列化适用于文件和字符串流
Overloading the stream operators <<
for serialization and >>
for deserialization works well with file and string streams
您可以指定构造函数 Message (const char*) 以从 char* 构造.
You could specify a constructor Message (const char*) for constructing from a char*.
我喜欢使用静态方法进行反序列化,例如:
I am a fan of static methods for deserialization like:
Message {
...
static bool desirialize (Message& dest, char* source);
}
因为您可以在反序列化时直接捕获错误.
since you could catch errors directly when deserializing.
并且您提出的版本是可以的,在应用评论中的修改时受到尊重.
And the version you proposed is ok, when applying the modifications in the comments are respected.
这篇关于C++中的对象序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!