Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map a file into the virtual memory manager in OSX?

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?

like image 228
user3275597 Avatar asked Oct 20 '22 12:10

user3275597


2 Answers

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);
like image 105
Graham Perks Avatar answered Oct 22 '22 22:10

Graham Perks


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.

like image 31
Ken Thomases Avatar answered Oct 22 '22 23:10

Ken Thomases