Skip to content

Instantly share code, notes, and snippets.

@OneSadCookie
Created November 20, 2014 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OneSadCookie/956c6276bf5e7b1bc7b8 to your computer and use it in GitHub Desktop.
Save OneSadCookie/956c6276bf5e7b1bc7b8 to your computer and use it in GitHub Desktop.
// c++ -std=c++11 -fobjc-arc -framework Foundation test.mm && ./a.out
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface X : NSObject
- (void)method1;
- (int)method2:(int)arg;
@end
@implementation X
- (void)method1
{
sleep(1);
}
- (int)method2:(int)arg
{
sleep(2);
return arg;
}
@end
struct probie_timer
{
probie_timer() : _start([NSDate timeIntervalSinceReferenceDate]) {}
~probie_timer() { NSLog(@"%f", [NSDate timeIntervalSinceReferenceDate] - _start); }
private:
NSTimeInterval _start;
};
template<class C, class R, class... Args>
void probie(SEL s)
{
Method orig = class_getInstanceMethod([C class], s);
IMP imp = method_getImplementation(orig);
auto block = [=](C *self, Args... args) -> R {
probie_timer t;
return ((R (*)(id, SEL, Args...))imp)(self, s, args...);
};
IMP new_imp = imp_implementationWithBlock(block);
method_setImplementation(orig, new_imp);
}
int main()
{
probie<X, void>(@selector(method1));
probie<X, int, int>(@selector(method2:));
X *x = [X new];
[x method1];
printf("%d\n", [x method2:3]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment