无法将UnsafeMutableRawPointer的值转换为BluetoothDeviceAddress

时间:2017-09-23 14:59:19

标签: swift xcode bluetooth bluetooth-lowenergy

我试图转换此源代码:

BluetoothDeviceAddress *deviceAddress = malloc(sizeof(BluetoothDeviceAddress));
对斯威夫特来说,这给了我:

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

但是,我发现在Swift 3/4中,sizeof不再使用了,但这不是我的错误,Xcode返回:

"无法转换类型' UnsafeMutableRawPointer的值!'指定类型' BluetoothDeviceAddress'"

我尝试更改为malloc(MemoryLayout<BluetoothDeviceAddress>.size),但仍然是同样的错误。

编辑: 正如MartinR的评论中提出的那样,我尝试改为let deviceAddress = BluetoothDeviceAddress() 但是当我想初始化IOBluetoothDevice时,我仍然会收到错误(selectedDevice是IOBluetoothDevice的var):

self.selectedDevice = IOBluetoothDevice(address: deviceAddress)

错误:无法转换类型&#39; BluetoothDeviceAddress&#39;的值预期参数类型&#39; UnsafePointer!&#39;

最佳,

安托

1 个答案:

答案 0 :(得分:1)

回答直接问题:从原始内容中获取键入的指针 指针在Swift中称为“绑定”,并使用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,而是使用allocate / release方法 斯威夫特的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)
// ...