C/ObjC调用Swift函数

C/ObjC调用Swift函数

  • 修饰符cdecl
    编译器会为当前swift函数增加wrapper函数,方便从C调用
  • 修饰符objc
    注意,在ObjC类前和类方法前都要加该修饰符。编译器会为所有类方法增加wrapper方法,方便从ObjC调用
  • 修饰符silgen_name
    编译器会直接将当前函数编译成C函数,在Swift中调用时也以C函数方式进行
@_cdecl("runoob0_cdecl")
func runoob0(i:Int) -> Int {
    return i+1;
}

@objc
class runoobcls:NSObject {
    @objc func runoob1(i:Int) -> Int {
        return i+1;
    }
}

@_silgen_name("runoob2_silgen") func runoob2(i:Int) -> Int {
    for i in [1...1000] {
        print(i)
    }
    return i+1;
}

Swift调用ObjC

var ret1 = runoob0(i:0);
let g:runoobcls = runoobcls();
var ret2 = g.runoob1(i:1);
var ret3 = runoob2(i:2);
print("in swift \(ret1) \(ret2) \(ret3)")

ObjC调用Swift

extern int runoob0_cdecl(int);
int ret0 = runoob0_cdecl(10);
runoobcls* g = [[objc_getClass("testswift1.runoobcls") alloc] init];
int ret1 = [g runoob1WithI:11];
extern int runoob2_silgen(int);
int ret2 = runoob2_silgen(12);
NSLog(@"in c %d %d %d", ret0, ret1, ret2);