Swift:无法将“UnsafeMutablePointer”类型的值转换为预期的参数类型“UnsafeMutablePointer”
Posted
技术标签:
【中文标题】Swift:无法将“UnsafeMutablePointer”类型的值转换为预期的参数类型“UnsafeMutablePointer”【英文标题】:Swift: Cannot convert value of type 'UnsafeMutablePointer' to expected argument type 'UnsafeMutablePointer' 【发布时间】:2016-11-02 10:29:06 【问题描述】:更新到 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()
我把它转换成这个代码,在第三行我得到一个错误
...无法将“UnsafeMutablePointer”类型的值转换为预期的参数类型“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()
有谁知道如何摆脱这个?
【问题讨论】:
【参考方案1】: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()
将“项目”的数量作为参数,而不是数量
字节。)
但请注意,您的方法会泄漏内存,分配的内存
被取消初始化(使用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
【讨论】:
【参考方案2】:您也可以在扩展中使用以下语法
extension Data
func castToCPointer<T>() -> T
var bytes = self.bytes
var val = withUnsafePointer(to: &bytes) (temp) in
return unsafeBitCast(temp, to: T.self)
return val
var data:NSData/NSMutableData
var bytes = data.bytes
var val = withUnsafePointer(to: &bytes) (temp) in
return unsafeBitCast(temp, to: T.self)
【讨论】:
以上是关于Swift:无法将“UnsafeMutablePointer”类型的值转换为预期的参数类型“UnsafeMutablePointer”的主要内容,如果未能解决你的问题,请参考以下文章
无法将“Swift._SwiftDeferredNSDictionary<Swift.String, Swift.String>”类型的值转换为“NSMutableDictionary”
无法将“Swift.Array<Any>”类型的值转换为“Swift.Dictionary<Swift.String, Any>”