Created
May 19, 2012 18:50
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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