gpt4 book ai didi

swift - 无法将 UnsafeMutableRawPointer 的值转换为 BluetoothDeviceAddress

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:14 28 4
gpt4 key购买 nike

我正在尝试转换此源代码:

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 是 IOBluetoothDevice 的一个变量):

self.selectedDevice = IOBluetoothDevice(address: deviceAddress)

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

最好的,

安托万

最佳答案

回答你的直接问题:Acquiring a typed pointer from a raw指针在 Swift 中称为“绑定(bind)”并通过 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 方法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有关原始指针和绑定(bind)的更多信息。

但是,直接创建该类型的值通常更容易并使用 & 将其作为 inout 表达式传递。示例:

var deviceAddress = BluetoothDeviceAddress()
// ...

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

关于swift - 无法将 UnsafeMutableRawPointer 的值转换为 BluetoothDeviceAddress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46380932/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com