Memory Mapped files, cast to type? alternative?

Started by
4 comments, last by Ace826 18 years, 8 months ago
So, if I have a memory mapped file... void *ptr_mmf, i have been told that it is a bad idea to cast it to what I am going to use it for, like casting it to a big struct or something. This true? Bad idea? What are the alternatives?
Advertisement
That isn't such a good idea because different compilers may pad the structures in the file differently. Also, if you wrote out the file in sections, things might get misaligned across different structures. Both of these tend to make things go boom (although the latter only on some archetectures).
O. Darn alignment. What is a good alternative? Should i just be using FILE *?

Thanks again.
Quote:Original post by Ace826
O. Darn alignment. What is a good alternative? Should i just be using FILE *?

The "best" (as in, most reliable) method is to read each variable in a struct from the file individually (and don't forget endian conversions). But that's a huge pain, and slow, too. I usually read structs from a file at a time, as the structs are designed very carefully to preserve alignment and compiler-added padding (or rather lack of padding). Usually I only use memory mapping in cases where the file is treated as a byte array (i.e. hashing the file).
There are several uses for memory-mapped files. One is to share data between processes on the same machine.

In this case, all those processes should be using the same executable, therefore would have compatible structure layouts.

As long as you don't ever move the file between machines, or need to keep its contents between versions of the program (where you might add / remove structure members or change compiler settings), you'll be fine.

I wrote a chat program which used a memory mapped file. That worked fine.

Mark
Thanks. Great info!

This topic is closed to new replies.

Advertisement