在SWIFT编程中如果想调用C语言编写的函数则需要通过桥接文件来实现。在桥接文件中通常使用的OC代码,在OC中就可以直接操作调用C的函数。
1. 在Swift中读C指针
下面桥接文件中的方法会返回一个int指针,即C术语里面的(int *):
@interface PointerBridge : NSObject {
int count;
}
- (int *) getCountPtr;
@end
@implementation PointerBridge
- (instancetype) init {
self = [super init];
if(self) {
count = 23;
}
return self;
}
- (int *) getCountPtr {
return &count;
}
@end
在SWIFT中调用桥接文件时可以通过如下方式获得int*的内容。
let bridge = PointerBridge()
let theInt = bridge.getCountPtr()
print(theInt.memory)
这里的theInt.memory得到的值就是23。
2. 在Swift中转递C指针给桥接文件
假如oc桥接文件中有如下的一个函数接口
- (void) setCountPtr:(int *)newCountPtr {
count = *newCountPtr;
}
此时在SWIFT代码中传给setCountPtr函数的参数需为int *类型。在SWIFT中可以通过UnsafeMutablePointer<Int32> 类型来操作。
let bridge = PointerBridge()
let theInt = bridge.getCountPtr()
print(theInt.memory)
let newIntPtr = UnsafeMutablePointer<Int32>.alloc(1)
newIntPtr.memory = 100
bridge.setCountPtr(newIntPtr)
print(theInt.memory) // 100
通过这种方式,bridge中的count就被修改为了100。需要注意的是给UnsafeMutablePointer<Int32>构造方法传入的参数是需要分配空间的对象的个数,在这里只需要一个Int32对象,所以我们传入1即可。
Reference:
http://www.youkuaiyun.com/article/2015-09-07/2825641
Swift与C交互指南
本文介绍了如何在Swift中调用C语言编写的函数,并详细解释了如何通过桥接文件进行C指针的读取和传递。包括使用Objective-C类作为桥梁,以及Swift中UnsafeMutablePointer的使用。
2395

被折叠的 条评论
为什么被折叠?



