Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 14th, 2012  |  syntax: None  |  size: 0.95 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // (C)2011 to3oo mi2ukam1 tmiz.net
  2. //
  3. // interposing on objc sample
  4. // $ g++ main.m -framework cocoa
  5. // $ ./a.out
  6. // 2011-12-20 12:12:37.159 a.out[533:903] hello
  7. // 2011-12-20 12:12:37.164 a.out[533:903] world
  8.  
  9. #include <cocoa/cocoa.h>
  10. #include <objc/objc-class.h>
  11.  
  12. // --- example instead of existing class
  13.  
  14. @interface AObject : NSObject {
  15.    
  16. };
  17.  
  18. -(void)sayHello;
  19.  
  20. @end
  21.  
  22. @implementation AObject
  23.  
  24. -(void)sayHello
  25. {
  26.     NSLog(@"hello");
  27. }
  28. @end
  29.  
  30. //
  31.  
  32. @implementation AObject(DYNA)
  33.  
  34. -(void)sayHello_new
  35. {
  36.     [self sayHello_new];
  37.     NSLog(@"world");
  38. }
  39.  
  40. @end
  41.  
  42. void interpose()
  43. {
  44.     Class aobj_class = objc_getClass("AObject");
  45.     Method a = class_getInstanceMethod(aobj_class,
  46.                                        @selector(sayHello));
  47.     Method b = class_getInstanceMethod(aobj_class,
  48.                                        @selector(sayHello_new));
  49.     method_exchangeImplementations(a, b);
  50. }
  51.  
  52. int main() {
  53.     interpose();
  54.     id aobj = [[AObject alloc] init];
  55.     [aobj sayHello];
  56.     [aobj release];
  57.     return 0;
  58. }