gpt4 book ai didi

Swift:无法将类型 'UnsafeMutablePointer' 的值转换为预期的参数类型 'UnsafeMutablePointer'

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:56 27 4
gpt4 key购买 nike

更新到 Swift 3 后,我的代码出现了一些问题。我在转换之前有这段代码:

extension NSData {
func castToCPointer<T>() -> T {
let mem = UnsafeMutablePointer<T>.alloc(sizeof(T.Type))
self.getBytes(mem, length: sizeof(T.Type))
return mem.move()
}
}

然后我将其转换为此代码,在第 3 行出现错误

... Cannot convert value of type 'UnsafeMutablePointer' to expected argument type 'UnsafeMutablePointer'

extension Data {
func castToCPointer<T>() -> T{
let mem = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T.Type>.size)
self.copyBytes(to: mem, count: MemoryLayout<T.Type>.size)
//self.copyBytes(to: mem, count: MemoryLayout<T.Type>.size)
return mem.move()
}
}

有谁知道如何摆脱这个?

最佳答案

copyBytes 需要一个 UnsafeMutableBufferPointer 作为参数:

extension Data {
func castToCPointer<T>() -> T {
let mem = UnsafeMutablePointer<T>.allocate(capacity: 1)
_ = self.copyBytes(to: UnsafeMutableBufferPointer(start: mem, count: 1))
return mem.move()
}
}

(allocate() 将“items”的数量作为参数,而不是字节。)

但是注意你的方法会泄漏内存,分配的内存被取消初始化(使用 move())但也必须是释放:

extension Data {
func castToCPointer<T>() -> T {
let mem = UnsafeMutablePointer<T>.allocate(capacity: 1)
_ = self.copyBytes(to: UnsafeMutableBufferPointer(start: mem, count: 1))
let val = mem.move()
mem.deallocate(capacity: 1)
return val
}
}

一个更简单的解决方案是(来自 round trip Swift number types to/from Data ):

extension Data {
func castToCPointer<T>() -> T {
return self.withUnsafeBytes { $0.pointee }
}
}

关于Swift:无法将类型 'UnsafeMutablePointer' 的值转换为预期的参数类型 'UnsafeMutablePointer',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40377642/

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