调用objc_msgSend方法在64位下崩溃解决方法

以前一直在非64位机器下测试一切正常的程序,在iPhone5s下平白无故崩溃。崩溃的位置是调用objc_msgSend时出现。通过一番辛苦搜索终于发现苹果官网上有一段这样的描述:html

Dispatch Objective-C Messages Using the Method Function’s Prototypeios

An exception to the casting rule described above is when you are calling the objc_msgSend function or any other similar functions in the Objective-C runtime that send messages. Although the prototype for the message functions has a variadic form, the method function that is called by the Objective-C runtime does not share the same prototype. The Objective-C runtime directly dispatches to the function that implements the method, so the calling conventions are mismatched, as described previously. Therefore you must cast the objc_msgSend function to a prototype that matches the method function being called.架构

Listing 2-14 shows the proper form for dispatching a message to an object using the low-level message functions. In this example, thedoSomething: method takes a single parameter and does not have a variadic form. It casts the objc_msgSend function using the prototype of the method function. Note that a method function always takes an id variable and a selector as its first two parameters. After the objc_msgSendfunction is cast to a function pointer, the call is dispatched through that same function pointer.app

Listing 2-14  Using a cast to call the Objective-C message sending functionside

- (int) doSomething:(int) x { ... }
- (void) doSomethingElse {
   int (*action)(id, SEL, int) = (int (*)(id, SEL, int)) objc_msgSend;
   action(self, @selector(doSomething:), 0);
}

 

貌似是说不能直接使用objc_msgSend的原型方法来匿名调用,不然会出现异常。结果尝试了上面的方法强制转换成必定的方法后,再次运行没有崩溃了,Luck!!测试

原文来自:https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/ConvertingYourAppto64-Bit/ConvertingYourAppto64-Bit.htmlui

 

补充说明(2015-8-5):this

对于返回结构体的方法,若是使用objc_msgSend进行调用是会抛出异常EXC_BAD_ACCESS:spa

CGSize (*action)(id, SEL, int) = (CGSize (*)(id, SEL, int)) objc_msgSend;
CGSize size = action(self, @selector(doSomething:), 0);

这样的作法是有可能会出现崩溃问题的(可是不必定每一个程序都必然会出现),通过查看官方文档发现,objc_msgSend有一个扩展版本objc_msgSend_stret,是专门用于处理返回结构体的状况,所以把代码改成以下所示便可解决问题:prototype

CGSize (*action)(id, SEL, int) = (CGSize (*)(id, SEL, int)) objc_msgSend_stret;
CGSize size = action(self, @selector(doSomething:), 0);

注:此调整只有在armv7架构下须要进行调整,若是包含arm64则不须要。

相关文章
相关标签/搜索