【发布时间】:2011-03-16 07:05:24
【问题描述】:
我想要做的是,让类消息序列化和反序列化它的自我。不是进入或来自文件,而是作为字符串或 cstring 进入或来自二进制序列。
消息.h:
class Message
{
private:
int message_id;
int sender_id;
std::string sender_data;
Message ();
public:
Message (int id, std::string data);
virtual ~Message ();
virtual const char* Serialize ();
virtual void Deserialize (const char* buf);
virtual void Print ();
};
Message.cpp:
const char* Message::Serialize ()
{
char buf[1024];
// This will work somehow. I get the object and then glibc
// detects double free or corruption, because i write into buf
// and not into a file.
// std::ofstream out_stream(buf, std::ios::binary);
// out_stream.write((char *)this, sizeof(*this));
// out_stream.close();
// Why this won't work? I didn't get it.
std::stringstream out_stream(buf, std::ios::binary);
out_stream.write((char *)this, sizeof(*this));
std::string str(buf);
std::cout << str << std::endl
<< buf << std::endl;
return str.c_str();
}
void Message::Deserialize (const char* buf)
{
std::ifstream in_stream(buf, std::ios::binary);
in_stream.read((char*)this, sizeof(*this));
in_stream.close();
}
主要:
#include "Message.h"
int main (int argc, int argv[])
{
Message msg1(12345, "some data");
Message msg2(12346, "some other data");
msg1.Print();
msg2.Print();
msg2.Deserialize(msg1.Serialize());
msg1.Print();
msg2.Print();
return 0;
}
输出:
消息:0 客户端:12345 数据:一些数据
消息:1 客户:12346 数据:一些其他数据
消息:0 客户端:12345 数据:一些数据
消息:1 客户:12346 数据:一些其他数据
有什么建议吗? 问候梅沙
【问题讨论】:
-
将 this 转换为 char* 是未定义的行为,如果 Message 恰好是多态的,就会发生坏事。
-
好吧,您正在使用虚函数......它会生成存储在对象结构开头的虚函数表。
标签: c++ serialization binary stream