Skip to content

Instantly share code, notes, and snippets.

@rraallvv
Created May 9, 2015 18:04
Show Gist options
  • Select an option

  • Save rraallvv/a3cfcfb9d11b3b28742f to your computer and use it in GitHub Desktop.

Select an option

Save rraallvv/a3cfcfb9d11b3b28742f to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
static NSMethodSignature *BlockSignature(id blockObj) {
struct Block {
void *isa;
int flags;
int reserved;
void *invoke;
struct Descriptor {
unsigned long reserved;
unsigned long size;
void *rest[1];
} *descriptor;
};
struct Block *block = (__bridge void *)blockObj;
int copyDisposeFlag = 1 << 25;
int signatureFlag = 1 << 30;
assert(block->flags & signatureFlag);
int index = 0;
if(block->flags & copyDisposeFlag)
index += 2;
const char *types = block->descriptor->rest[index];
NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes: types];
while([signature numberOfArguments] < 2) {
types = [[NSString stringWithFormat: @"%s%s", types, @encode(void *)] UTF8String];
signature = [NSMethodSignature signatureWithObjCTypes: types];
}
return signature;
}
int main(void) {
@autoreleasepool {
int captured = 123;
void (^block)(int, NSString *) = ^(int testArgument, NSString *anotherTestArgument) {
NSLog(@"%d %d %@", captured, testArgument, anotherTestArgument);
};
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:BlockSignature(block)];
[invocation setTarget:block];
[invocation setArgument:&(int){ 456 } atIndex: 1];
[invocation setArgument:&(NSString *){ @"string" } atIndex: 2];
[invocation invoke];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment