Skip to content

Instantly share code, notes, and snippets.

@armadsen
Created May 19, 2012 18:50
Show Gist options
  • Save armadsen/2731937 to your computer and use it in GitHub Desktop.
Save armadsen/2731937 to your computer and use it in GitHub Desktop.
Simple example of getting a function pointer to an Objective-C method and calling it
// To compile and test this from the command line:
//
// $> clang FunctionPointerFromMethod.m -ObjC -framework Foundation -fobjc-arc
// $> ./a.out
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
- (void)someMethodThatTakesOneStringArgument:(NSString *)string;
@end
@implementation MyClass
- (void)someMethodThatTakesOneStringArgument:(NSString *)string
{
NSLog(@"Here's the string: %@", string);
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
MyClass *obj = [[MyClass alloc] init];
IMP methodIMP = [obj methodForSelector:@selector(someMethodThatTakesOneStringArgument:)];
void (*functionPointer)(id, SEL, NSString*) = (void (*)(id, SEL, NSString*))methodIMP;
// Then call it:
functionPointer(obj, @selector(someMethodThatTakesOneStringArgument:), @"hello");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment