2017-09-23 7 views
2

にUnsafeMutableRawPointerの値を変換できません。 4、sizeofはもう使用されませんが、これは私のエラーではありません。は、私は、このソースコードを変換しようとしているBluetoothDeviceAddress

"タイプ 'UnsafeMutableRawPointer!'の値を変換できません。指定されたタイプ 'BluetoothDeviceAddress' "

私はmalloc(MemoryLayout<BluetoothDeviceAddress>.size)に変更しようとしましたが、同じエラーです。

EDIT: MartinRのコメントで提案されているように、私はlet deviceAddress = BluetoothDeviceAddress() に変更してみましたが、私はIOBluetoothDeviceを初期化したいときに、私はまだ(selectedDeviceがIOBluetoothDeviceためのVAR)でエラーが出ます:

self.selectedDevice = IOBluetoothDevice(address: deviceAddress) 

エラー: 'BluetoothDeviceAddress'タイプの値を期待される引数タイプ 'UnsafePointer!'に変換できません。

ベスト、

アントワーヌ

+0

なぜ*メモリを割り当てる必要がありますか?単に 'let/var deviceAddress = BluetoothDeviceAddress()'ではないのですか? –

+0

@MartinRは動作しません。私の編集を参照してください – Antoine

答えて

1

はあなたの直接の質問に答えるために:代わりに

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) 

bindMemory()とスウィフトの "結合" およびdoneと呼ばれている生 ポインタから入力されたポインタを取得malloc/freeの場合、割り当て/解放メソッド をUnsafe(Mutable)Pointer Swiftで使用します。

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