Skip to content

Instantly share code, notes, and snippets.

@jverkoey
Created June 25, 2012 01:03
Show Gist options
  • Save jverkoey/2985830 to your computer and use it in GitHub Desktop.
Save jverkoey/2985830 to your computer and use it in GitHub Desktop.
Memory mapping in Objective-C
const char* cstr = [string UTF8String];
void* anon = mmap(0, sizeof(char) * (string.length + 1), PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, 0, 0);
if (anon == MAP_FAILED) {
NSLog(@"Failed to map memory.");
return;
}
strcpy(anon, cstr);
// How do I get a file descriptor for use here?
markdownin = fdopen(fd, "r");
@jverkoey
Copy link
Author

As this stands I'm able to map the memory, but I don't have a file descriptor that I can use between mmap and f*open methods so that I can create a FILE pointer.

@vgrichina
Copy link

  1. Use shm_open to obtain file descriptor.
  2. Use file descriptor from shm_open in mmap.
  3. Use fdopen to obtain FILE pointer from file descriptor.

@jverkoey
Copy link
Author

jverkoey commented Jun 25, 2012 via email

@jverkoey
Copy link
Author

Here's the latest. Still not working sadly and I'm not sure what the culprit is.

const char* path = "/string1524";
int stringSize = sizeof(char) * (string.length + 1);
int fd = shm_open(path, O_RDWR | O_CREAT);
ftruncate(fd, stringSize);
void* anon = mmap(0, stringSize, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
if (anon == MAP_FAILED) {
  NSLog(@"Failed to map memory.");
}
strcpy(anon, cstr);

// This returns a FILE*, but when trying to read from it I get garbage data.
markdownin = fdopen(fd, "r");

@vgrichina
Copy link

Unfortunately I also in result had no success in making it work on OS X / iOS.

However I found alternative solution which even isn't an ugly hack – http://developer.apple.com/library/ios/#documentation/System/Conceptual/ManPages_iPhoneOS/man3/fropen.3.html
You can just specify your function to read stream.

There is example here https://redmine.openinfosecfoundation.org/attachments/105/0001-fmemopen-wrapper-added-fix-compilation-problems-on-m.patch

@jverkoey
Copy link
Author

I used this code linked to by poTomek on twitter and it worked beautifully:

https://github.com/ingenuitas/python-tesseract/blob/master/fmemopen.c

@jverkoey
Copy link
Author

Looks very similar to the example given in your links :)

@jverkoey
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment