您的位置:首页 > 移动开发 > IOS开发

iOS 64-bit architecture 使用objc_msgSend要小心

2016-08-11 21:34 357 查看
在iOS64-bit下,使用objc_msgSend直接调用方法会造成崩溃,报错xc_bad_access,具体原因看苹果文档https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/ConvertingYourAppto64-Bit/ConvertingYourAppto64-Bit.html

Dispatch Objective-C Messages Using the Method Function’s Prototype 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, the

doSomething: 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_msgSend function is cast to a function pointer, the call is

dispatched through that same function pointer.

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

functions

- (int) doSomething:(int) x { … }

- (void) doSomethingElse {

int (action)(id, SEL, int) = (int ()(id, SEL, int)) objc_msgSend;

action(self, @selector(doSomething:), 0); }

大致就是,OBJC_EXPORT id objc_msgSend(id self, SEL op, …)最后的参数需要声明类型,所以使用应该像这样

void (*objcMsgSend)(id,SEL,id) = (void *)objc_msgSend;
objcMsgSend(plugin, selector, cmd);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS 64-bit msgSend