cross-platform binary files (c++)

i’m interested in serializing my model objects to binary files, but i’m worried about cross-platform issues.

the simplest way to serialize objects – taking a pointer to the object and streaming sizeof() bytes – is certainly not a versatile solution. i’m afraid that it may even be compiler specific, as different c++ implentations are allowed certain freedoms with generated code.

another approach, streaming only the data from an object, will run into trouble as well, because primitive data types may vary in size from system to system depending on the size of a machine word, etc. endian issues also arise.

i am sure that other people have long ago solved these problems in various ways, and i’m interested in finding references to those solutions.

Don’t even think about the “streaming sizeof() bytes” approach. Never mind compiler-specific, what’s going to happen when an object includes pointers? Uh-huh. Boom.

If you want cross-platform, you should be either storing all data in fixed-sized types or converting it to such types before reading/writing. By fixed-size types I mean something like “int32”, which is typedef’d to a platform/compiler-specific 32-bit integer type. Keep all these typedefs in a single header, with conditional compilation blocks for different platforms.

For the endian problem, the usual approach is to have a “byte-order mark” as the very first thing in a file. This is a number with a known value for a given endianness. F’rinstance, if your BOM is defined as 0xffee for big-endian, and the first int16 of your file comes back as 0xeeff, you know you have a little-endian file and need to do some conversions. Or you define a fixed endianness for your file format and do the conversions while writing, it’s up to you.

Not really an OpenGL question, but I hope it helps a bit.

thanks! this helps some. gives me something to look at.

i realize it’s not exactly an opengl question, but with much opengl development being cross-platform, i knew that i could get some leads. =)