2017-09-23 58 views
2

我想轉換此源代碼:不能UnsafeMutableRawPointer的值轉換爲BluetoothDeviceAddress

BluetoothDeviceAddress *deviceAddress = malloc(sizeof(BluetoothDeviceAddress)); 

斯威夫特,這給了我:

let deviceAddress: BluetoothDeviceAddress = malloc(sizeof(BluetoothDeviceAddress)) 

但是,我發現,在斯威夫特3/4,sizeof不再使用,但這不是我的錯誤,Xcode返回:

「無法轉換'UnsafeMutableRawPointer!'類型的值到指定類型「BluetoothDeviceAddress」「

我試圖更改爲malloc(MemoryLayout<BluetoothDeviceAddress>.size)但仍然是相同的錯誤。

編輯: 作爲由MartinR的意見建議,我試圖改變到let deviceAddress = BluetoothDeviceAddress() 但後來當我想初始化IOBluetoothDevice,我還得到一個錯誤(selectedDevice是IOBluetoothDevice一個VAR):

self.selectedDevice = IOBluetoothDevice(address: deviceAddress) 

錯誤:無法將類型'BluetoothDeviceAddress'的值轉換爲期望的參數類型'UnsafePointer!'

最佳,

安東尼

+0

爲什麼你必須*分配內存?爲什麼不只是'讓/ var deviceAddress = BluetoothDeviceAddress()'? –

+0

@MartinR無法正常工作,請參閱我的編輯 – Antoine

回答

1

要回答你直接的問題:從原始 指針獲取類型的指針斯威夫特被稱爲「綁定」並完成與bindMemory()

let ptr = malloc(MemoryLayout<BluetoothDeviceAddress>.size)! // Assuming that the allocation does not fail 
let deviceAddressPtr = ptr.bindMemory(to: BluetoothDeviceAddress.self, capacity: 1) 
deviceAddressPtr.initialize(to: BluetoothDeviceAddress()) 
// Use deviceAddressPtr.pointee to access pointed-to memory ... 

let selectedDevice = IOBluetoothDevice(address: deviceAddressPtr) 
// ... 

deviceAddressPtr.deinitialize(count: 1) 
free(ptr) 

相反的malloc/free,可以使用Swift中的Unsafe(Mutable)Pointer的分配/釋放方法 :

let deviceAddressPtr = UnsafeMutablePointer<BluetoothDeviceAddress>.allocate(capacity: 1) 
deviceAddressPtr.initialize(to: BluetoothDeviceAddress()) 
// Use deviceAddressPtr.pointee to access pointed-to memory ... 

let selectedDevice = IOBluetoothDevice(address: deviceAddressPtr) 
// ... 

deviceAddressPtr.deinitialize(count: 1) 
deviceAddressPtr.deallocate(capacity: 1) 

有關原始指針和綁定的更多信息,請參閱SE-0107 UnsafeRawPointer API

然而,它通常更容易創建該類型直接 的值並傳遞作爲INOUT表達與&。例如:

var deviceAddress = BluetoothDeviceAddress() 
// ... 

let selectedDevice = IOBluetoothDevice(address: &deviceAddress) 
// ... 
+0

令人驚歎的是,它工作完美,謝謝你的學習! – Antoine

相關問題