Im a little confused on how mmap()
works with the frameworks on iOS or OSX.
If a file is mapped to virtual memory using mmap()
and data is requested from it, the the kernel pages in the data to RAM. How does this actually affect how one creates objects?
If one usually creates an object using alloc
/init
, the memory block is allocated and the object initiated. But what if the data resides in virtual memory, in a mmap
'ed file? Does the alloc
need to be called on the object? Does the allocated memory for the object get filled with the data from virtual memory? Or does one skip the alloc
call and just pass in the pointer to the data in virtual memory?
e.g. an image or a sound file, if I know where the file is in virtual memory, how would I setup the object?
If one allocates the data, doesn't it get duplicated if the data is already paged into RAM?
I was thinking that using memory from virtual addresses would remove the need to allocate on the heap.
If you only have one object you are storing in the mmaped space, then you simply skip the alloc and use the location directly. However, normally you will have more than one object, and now you are into managing it yourself. Typically at least some portion of it will be laid out in a fixed manner, so that both processes know where to find things. Instead of pointers you get the fun of using offsets from the start of the arena, since that works in both processes' address space.
In essence, you're given a chunk of memory, as if you'd done one big malloc/alloc and you get to play around within it.
If you have, say
void *p = mmap( <appropriate arguments> );
and you want to put an object of type foo at offset 200, you would say
foo *f = (foo *)p+200;
and now you can manipulate f in all the normal ways, subject to f not containing any pointers into the mmapped space. It is generally good discipline to substitute offsets for such pointers, and then when you need to follow one, you can convert it to a pointer (by adding p).