Skip to content

Commit

Permalink
add BlockFptr convenience function
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeash committed Sep 18, 2010
1 parent 82660d7 commit 764463c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions MABlockClosure.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@
- (void *)fptr;

@end

// convenience function, returns a function pointer
// whose lifetime is tied to 'block'
// block MUST BE a heap block (pre-copied)
// or a global block
void *BlockFptr(id block);
16 changes: 16 additions & 0 deletions MABlockClosure.m
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#import "MABlockClosure.h"

#import <assert.h>
#import <objc/runtime.h>
#import <sys/mman.h>


Expand Down Expand Up @@ -286,3 +287,18 @@ - (void *)fptr
}

@end

void *BlockFptr(id block)
{
@synchronized(block)
{
MABlockClosure *closure = objc_getAssociatedObject(block, BlockFptr);
if(!closure)
{
closure = [[MABlockClosure alloc] initWithBlock: block];
objc_setAssociatedObject(block, BlockFptr, closure, OBJC_ASSOCIATION_RETAIN);
[closure release]; // retained by the associated object assignment
}
return [closure fptr];
}
}
5 changes: 5 additions & 0 deletions main.m
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@ int main(int argc, char **argv)
NSRect r = ((NSRect (*)(void))[closure fptr])();
NSLog(@"%@", NSStringFromRect(r));
[closure release];

block = [^(NSString *s) { return [s stringByAppendingFormat: @" %s", argv[0]]; } copy];
NSString *strObj = ((id (*)(id))BlockFptr(block))(@"hello");
NSLog(@"%@", strObj);
[block release];
}

0 comments on commit 764463c

Please sign in to comment.