Swift 無法直接使用 C 類型,Apple 提供了對應的 Swift 類型封裝。本文整理基本類型映射表與指針類型映射表,並演示構造方法與互轉技巧。
| C 類型 | Swift 類型 | 構造示例 |
|---|---|---|
| signed char | CChar / Int8 | CChar(65) |
| unsigned char | CUnsignedChar / UInt8 | CUnsignedChar(255) |
| short | CShort / Int16 | CShort(32767) |
| unsigned short | CUnsignedShort / UInt16 | CUnsignedShort(65535) |
| int | CInt / Int32 | CInt(42) |
| unsigned int | CUnsignedInt / UInt32 | CUnsignedInt(42) |
| long | CLong / Int (64位) | CLong(1000) |
| unsigned long | CUnsignedLong / UInt | CUnsignedLong(1000) |
| long long | CLongLong / Int64 | CLongLong(1_000_000) |
| unsigned long long | CUnsignedLongLong / UInt64 | CUnsignedLongLong(1_000_000) |
| float | CFloat / Float32 | CFloat(3.14) |
| double | CDouble / Float64 | CDouble(3.14159) |
| bool | CBool | CBool(true) |
let swiftInt = 80 let cInt = CInt(swiftInt) // Int -> CInt let cUChar = CUnsignedChar(swiftInt) // Int -> unsigned char let cUInt = CUnsignedInt(swiftInt) // Int -> unsigned int // 反向:C 類型 -> Swift 原生 let backToInt = Int(cInt) let backToUInt = UInt(cUInt)
| C 指針 | Swift 類型 | 說明 |
|---|---|---|
| const T* | UnsafePointer<T> | 不可變指針,需手動管理內存 |
| T* | UnsafeMutablePointer<T> | 可變指針,可 alloc/init/deinit/dealloc |
| T** / 複雜指針 | AutoreleasingUnsafeMutablePointer<T> | 自動釋放指針,用於 in-out 參數 |
| void* / 無法表示 | OpaquePointer | 不透明指針,類型擦除 |
init(_ other: OpaquePointer)、init(_ from: UnsafeMutablePointer<T>)、init(_ from: UnsafePointer<T>)pointee (Swift 3+ 替代 memory) 只讀訪問值successor() / predecessor() 移動指針allocate(capacity: Int) → initialize(to: T) / initialize(repeating: T, count: Int)deinitialize(count: Int) → deallocate()(成對調用)ptr[i] 或 pointee函數參數標記為此類型時,調用者傳入的變量會被複製到無所有權緩衝區,函數返回時寫回。常用於 C API 的雙重指針輸出參數。
unsafe,集中封裝在工具層,業務代碼不直接接觸。
