将对象转换为char *以保存/加载 [英] Casting an Object to char* for saving/loading

查看:81
本文介绍了将对象转换为char *以保存/加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题。

我正在写一个加载/保存函数,用于从保存的文件获取平面几何数据。所涉及的对象是从其中具有大量数据的类实例化的,但是它们仅使用简单的旧数据,并且没有指针/分配的存储器等。

I'm writing a loading/saving function for getting plain geometry data from a saved file. The objects involved are instanced from classes with a lot of data in them, but they all use just plain old data, and no pointers/allocated memory and the like.

它可以加载文件到一个分配的char *数组,类型转换,说,几何*,并且安全地期望一切都不扰乱,假设我做了相同的反向的事情保存(typecasting数组到char *,并写它文件)?

Is it possible to load the file into an allocated char* array, typecast that to, say, Geometry* , and safely expect everything to not get scrambled assuming I did the same reversed thing when saving (typecasting the array to char* and writing it to file)?

如果我试图访问数组,当它指向一个char *指针,或一个int *或任何其他指针类型,

If I attempt to access the array when it is pointed to by a char* pointer, or a int*, or any other pointer type, is there any special considerations I need to take?

推荐答案


是否可以将文件加载到
一个分配的char *数组,typecast
,例如,Geometry *

Is it possible to load the file into an allocated char* array, typecast that to, say, Geometry*

这是可能的。我做了一个类似的工作。我使用两个链 static_cast 来执行此操作:

It's possible. I've done a similar job. I had used two chained static_cast to do this, as:

char *buffer;
//..
Geometry *g = static_cast<Geometry *>(static_cast<void*>(buffer));

//reverse
buffer = static_cast<char*>(static_cast<void*>(g));

由于两个链接 static_cast 看起来很麻烦,我写了这个函数模板:

Since the two chained static_cast looks cumbersome, I've written this function template:

template<class To, class From>
To any_cast(From v)
{
    return static_cast<To>(static_cast<void*>(v));
}

然后使用它,

Geometry *g = any_cast<Geometry *>(buffer);

//reverse
buffer = any_cast<char*>(g);






查看此主题:


See this topic:

为什么我们在C ++中有两个链接的static_cast可以完成它的工作?

这篇关于将对象转换为char *以保存/加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆