IMP到底是什么?

IMP到底是什么?

IMP的定义从objc.h头文件中可以直接找到[1]:

typedef void (*IMP)(void /* id, SEL, ... */ ); 

也就是

typedef void (*IMP)(void); 

也就是参数为空, 返回值为空的函数指针.

IMP能直接调用么?

定义一个类:

@interface TestClass : NSObject

@end

@implementation TestClass

- (id)test:(NSInteger)arg {
    return nil;
}

@end

获取IMP并且调用:

int main(int argc, char * argv[]) {
    IMP testIMP = class_getMethodImplementation([TestClass class], @selector(test:));
    testIMP();

    return 1;
}

程序顺利执行没有崩溃, 并且可以断点断在test:方法里:
screenshot

IMP的返回值和参数怎么定?

但是感觉不对劲啊, test:方法的参数(NSInteger)arg并没有传呀? 怎么判断一个方法的具体参数呢:

Method testMethod = class_getInstanceMethod([TestClass class], @selector(test:));

而Method是[2]:

struct objc_method {
    SEL method_name                                          OBJC2_UNAVAILABLE;
    char *method_types                                       OBJC2_UNAVAILABLE;
    IMP method_imp                                           OBJC2_UNAVAILABLE;
}                                                            OBJC2_UNAVAILABLE;

从调试窗口的变量列表中可以看到:
screenshot

method_types是@24@0:8q16[4], 内容都是一个字符跟一个数字成对出现, 第一对表示返回值和参数长度(其中@表示返回值为id, 24表示参数长度为24字节),后面三对代表三个参数(@0表示参数是id而参数的偏移为0, :8表示参数是selector偏移为8,q16表示参数为long long偏移为16), 完整的type encoding参见参考[3].

也就意味着test:方法的IMP的类型应该是id (*IMP)(id, SEL, long long), 其中参数的第一个id是self, 第二个SEL是当前IMP对应的selector, 第三个long long就是test:arg参数. 更详细的介绍见参考[5].

参考

  1. objc.h: http://www.opensource.apple.com/source/objc4/objc4-680/runtime/objc.h
  2. runtime.h: http://www.opensource.apple.com/source/objc4/objc4-680/runtime/runtime.h
  3. Type Encodings: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
  4. What are the digits in an ObjC method type encoding string?: http://stackoverflow.com/questions/11491947/what-are-the-digits-in-an-objc-method-type-encoding-string
  5. Messaging: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtHowMessagingWorks.html#//apple_ref/doc/uid/TP40008048-CH104-TPXREF134
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值