I am trying to map a file into OS X's virtual memory manager. How do I do this on Mac OS X using Objective C?
Use mmap. e.g.
FILE* f = fopen(...);
// Map the file into memory.
// Need the file size.
fseek(f, 0, SEEK_END); // seek to end of file
off_t fileSize = ftello(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
mappedSize = fileSize;
mappedAddress = mmap(0, _mappedSize, PROT_READ, MAP_PRIVATE, f->_file, 0);
... use mappedAddress as a pointer to your data
// Finally free up
munmap(_mappedAddress, _mappedSize);
fclose(f);
Using mmap()
works, of course. Another option, given that you're using Cocoa, is to use NSData
or NSMutableData
. You can create the data object using -initWithContentsOfURL:options:error:
with NSDataReadingMappedIfSafe
or NSDataReadingMappedAlways
in the options. There are two different options because mapping a file is not necessarily safe. If the file is on a file system that may disappear spontaneously (network file system, removable drive), then having it mapped opens your app to crashes. The former option only maps if that's not likely to happen. Otherwise, it reads the data into memory. The latter option always maps, leaving it to you to cope with the potential for crashes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With