无法将UnsafeMutableRawPointer的值转换为BluetoothDeviceAddress

3

我正在尝试转换这段源代码:

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

转向 Swift,这给了我:

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

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

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

。我尝试改成malloc(MemoryLayout<BluetoothDeviceAddress>.size),但仍然出现相同的错误。 编辑: 根据MartinR在评论中提出的建议,我尝试改成let deviceAddress = BluetoothDeviceAddress(),但是当我想初始化IOBluetoothDevice时仍然会出错(selectedDevice是一个var for IOBluetoothDevice)。
self.selectedDevice = IOBluetoothDevice(address: deviceAddress)

错误: 无法将类型为 'BluetoothDeviceAddress' 的值转换为预期的参数类型 'UnsafePointer!'

祝好,

安东尼


为什么你必须分配内存?为什么不只是let/var deviceAddress = BluetoothDeviceAddress() - Martin R
@MartinR 没有起作用,请查看我的编辑。 - Antoine
1个回答

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)

在Swift中,与其使用malloc/free,一个更好的选择是使用Unsafe(Mutable)Pointer的allocate/release方法:

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)
// ...

太棒了,它完美地运行了,谢谢你教我这个!! - Antoine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接