Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

reading binary -> C++ structs

Name: Anonymous 2006-06-10 21:03

I'm writing a program in C++ to read in .geo format binary 3d graphic files.  I have a file spec that gives me plainly the struct of the various data blocks.  As a result, I can do this:

tPolygonObject getObjectEntry (ifstream& geoFile, udword address)
{  tPolygonObject tmpobj;
   geoFile.seekg(address);
   geoFile.read((char*)&tmpobj, sizeObjectEntry);
   return tmpobj; }

// function call
polyObject[i] = getObjectEntry(geoFile, memFinger);

Meaning, I can simply read a chunk and plunk it down into my struct variable, and all the data members will be what they're supposed to be without me worrying about them lining up.

The problem is, what if I alter the structs, by adding more member variables? If I put them at the end, will it fill up the original ones in the same way, and leave the new members empty? Or will it just FUBAR everything?

Name: Anonymous 2006-06-11 1:23

>>1

Perhaps.

This depends on the architecture in question, as well as the compiler, optimizations, and perhaps even the order that the members of the struct are defined in.  If your compiler is optimizing alignment within the data structure, e.g., and you add more members, the end optimization might be different and a direct binary plunking may no longer be valid.  Or it may be valid.  Who knows?

(This is why >>2's suggestion is only good for informal dev't or a very specific problem space, btw.  The fact that it builds and works on your machine doesn't imply that it will build and work on mine.  I might have a different compiler that optimizes alignment differently.  I might have an architecture with a different sort of alignment.  Etc.)

If you're insistent on modifying the existing struct, and you expect a limited use-space, go ahead and try it, see if it works.  You could also inspect the actual binary representation in memory to double check everything's as expected.

What you should be asking yourself, though, is why you want to change what exists instead of simply eating the cost of a copy, or (even better) the cost of a struct that contains your desired struct.  E.g.:

struct tPolygonObject{
  // blah
};

struct tMyPolygonObject{
  tPolygonObject p;
  // extra things you want on tPolygonObjects
};

You could still do your copy by referencing p.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List