場景:Swift 調用返回 C 指標的 OC 方法
// OC 端
@interface PointerBridge : NSObject
- (int *)getCountPtr;
- (void)setCount:(int)newCount;
- (void)setCountPtr:(int *)newCountPtr;
@end
@implementation PointerBridge {
int count;
}
- (instancetype)init { self=[super init]; if(self) count=23; return self; }
- (int *)getCountPtr { return &count; }
- (void)setCount:(int)v { count=v; }
- (void)setCountPtr:(int *)p { count=*p; }
@end
Swift 讀取指標
let bridge = PointerBridge()
let ptr = bridge.getCountPtr() // UnsafeMutablePointer
print(ptr) // 記憶體位址
print(ptr.pointee) // 23 (Swift 3+ 用 pointee, 舊版 memory)
// 透過 OC 修改後,指標指向的值同步更新
bridge.setCount(1000)
print(ptr.pointee) // 1000
// ⚠️ 複製值而非指標
let copied = ptr.pointee // Int32 = 23
bridge.setCount(1000)
print(copied) // 仍為 23,失去指標特性
Swift 建立指標傳給 OC
let newPtr = UnsafeMutablePointer.allocate(capacity: 1)
newPtr.pointee = 100
bridge.setCountPtr(newPtr)
print(ptr.pointee) // 100
// 釋放記憶體
newPtr.deallocate()
關鍵類型對照
| C/OC 型別 | Swift 型別 |
int * | UnsafeMutablePointer |
const int * | UnsafePointer |
float * | UnsafeMutablePointer |
總結
UnsafeMutablePointer 是 C 指標在 Swift 的泛型封裝。
- 使用
.allocate(capacity:) 配置記憶體,.deallocate() 釋放。
- 讀寫值用
.pointee(Swift 3+),舊版 .memory。
- 避免將
.pointee 複製給值型別變數,否則斷開指標關係。