objc_msg发送和工会

时间:2013-07-15 19:12:46

标签: objective-c objective-c-runtime

我有一个与objc_msgSend运行时调用有关的问题,当我有返回一些联合的方法时。

我通过libffi调用objc_msgSend函数,如果我有小于16B的union,一切都很好,但是如果union的大小大于16B,我会遇到seg错误。 我尝试使用objc_msgSend_stret函数,然后传递,但是我得到了返回union的错误值,而且我不确定调用哪个函数。

有没有人对目标c中的联合有所了解,它们如何在objc运行时中处理?

1 个答案:

答案 0 :(得分:5)

当您使用objc_msgSend时,这是一个HUUUUGE问题;基本上,大多数ABI喜欢将它们的返回值放在寄存器中(这里是勇敢和好奇的所有血腥细节:http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/LowLevelABI/000-Introduction/introduction.html)但是有些对象无法放入寄存器(这就是联合大小&lt的原因) ; = 16适合你工作)。您需要使用您希望将联盟填入的地址调用objc_msgSend_stret

另一个好的参考:http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/objc_msgSend_stret

解决方案:不是投射和调用objc_msgSend,而是投射并致电objc_msgSend_stret

void objc_msgSend_stret(void * stretAddr, id theReceiver, SEL theSelector,  ...)

所以你的演员阵容(如using objc_msgSend to call a Objective C function with named arguments):

union myUnion {
    int a, b;
    char c;
    double d;
};

// For objc_msgSend_stret
void (*objc_msgSend_stretTyped)(union myUnion* stretAddr, id self, SEL _cmd, float bar) = (void*)objc_msgSend_stret;

union myUnion u;
float pi = 4;

objc_msgSend_stretTyped(&u, obj, sel_getUID(sel), pi);

编辑 - 跳过以上所有代码

以下是我设法让objc_msgSend_stret工作的方法:

#import "ViewController.h"
#import <objc/runtime.h>
#import <objc/objc.h>

@interface ViewController ()

@end

union myUnion {
    int myArray[32];
    int a,b,c,d;
};

void doStuff(id obj, SEL sel);

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    doStuff(self, @selector(doStuff:));
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (union myUnion) doStuff: (int)myInt {
    NSLog(@"Pi equals %d", myInt);
    union myUnion u;
    for(int i=0; i<32; i++) {
        u.myArray[i] = i*i*i*i-1;
    }
    return u;
}

@end

void doStuff(id obj, SEL sel) {
    int pi = 4;
    NSLog(@"myUnion is: %luB", sizeof(union myUnion));
    NSLog(@"Sizeof(int) = %luB ... Sizeof(char) = %lub ... sizeof(double) = %luB", sizeof(int), sizeof(char), sizeof(double));

    union myUnion u = ((union myUnion(*)(id, SEL, int))objc_msgSend_stret)(obj, sel, pi);
    NSLog(@"Union u = {%d, %d, %d, %d}", u.myArray[30], u.myArray[29], u.myArray[28], u.myArray[27]);
}