0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101

3 Answers3

2

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?

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Oh, thanks! I always only used the generic "(Geometry*)buffer;" thing. I'll have to look up how static_cast differs. But why was the static cast to void* needed..? – Anne Quinn Feb 20 '11 at 06:47
  • @Clairvoire: That is needed, otherwise it'll not compile! – Nawaz Feb 20 '11 at 06:50
0

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.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • Endianness, I assume that could cause variables with 2 or 4 words to have them reversed? I didn't think of that, I'm glad you brought that up! – Anne Quinn Feb 20 '11 at 06:58
  • @Clairvoire: Yes, that can lead to things being reversed. Different padding and word sizes can also cause problems. Use a serialization library if you care about those things. – Jeremiah Willcock Feb 20 '11 at 07:00
0

Consider using a library for serialization, such as protobuf

jterrace
  • 64,866
  • 22
  • 157
  • 202