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?
Consider using a library for serialization, such as protobuf
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 notint*
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.It's possible. I've done a similar job. I had used two chained
static_cast
to do this, as:Since the two chained
static_cast
looks cumbersome, I've written this function template:Then used it as,
See this topic:
Why do we have reinterpret_cast in C++ when two chained static_cast can do its job?