Casting an Object to char* for saving/loading

2019-04-17 11:48发布

问题:

I have a small question.

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.

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)?

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?

回答1:

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

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));

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));
}

Then used it as,

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

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

See this topic:

Why do we have reinterpret_cast in C++ when two chained static_cast can do its job?



回答2:

You can write out an array of POD objects (that don't contain pointers) as bytes and then read them back in. The casts you propose will do that; you need to use char* and not int* to avoid problems with type-based alias analysis. However, you would need to read them in on a system with the same word size, endianness, and struct layout as the machine used to write them out.



回答3:

Consider using a library for serialization, such as protobuf