297
of objects into a binary fi le, we need to visit each object once (and only once)
in an arbitrary order and write each object’s memory image into the fi le se-
quentially. This has the eff ect of serializing the objects into a contiguous image
within the fi le, even when their memory images are not contiguous in RAM.
This is shown in Figure 6.7.
Because the objects’ memory images are now contiguous within the fi le,
we can determine the off set of each object’s image relative to the beginning of
the fi le. During the process of writing the binary fi le image, we locate every
pointer within every data object, convert each pointer into an off set, and store
those off sets into the fi le in place of the pointers. We can simply overwrite the
pointers with their off sets, because the off sets never require more bits to store
than the original pointers. In eff ect, an off set is the binary fi le equivalent of a
pointer in memory. (Do be aware of the diff erences between your development
platform and your target platform. If you write out a memory image on a 64-
bit Windows machine, its pointers will all be 64 bits wide and the resulting fi le
won’t be compatible with a 32-bit console.)
Of course, we’ll need to convert the off sets back into pointers when the
fi le is loaded into memory some time later. Such conversions are known as
pointer fi x-ups. When the fi le’s binary image is loaded, the objects contained
in the image retain their contiguous layout. So it is trivial to convert an off set
into a pointer. We merely add the off set to the address of the fi le image as a
whole. This is demonstrated by the code snippet below, and illustrated in
Figure 6.8.
6.2. The Resource Manager
Addresses: Offsets:
RAM Binary File
Object 1
Object 2
Object 3
Object 4
0x0
0x240
0x4A0
0x7F0
Object 1
Object 4
Object 2
Object 3
0x2A080
0x2D750
0x2F110
0x32EE0
Figure 6.7. In-memory object images become contiguous when saved into a binary fi le.