更新到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行我得到了错误
...无法转换类型的值&#39; UnsafeMutablePointer&#39;预期参数类型&#39; UnsafeMutablePointer&#39;
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()
}
}
有谁知道怎么摆脱这个?
答案 0 :(得分:7)
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
}
}
更简单的解决方案是(来自 {{3}}):
extension Data {
func castToCPointer<T>() -> T {
return self.withUnsafeBytes { $0.pointee }
}
}
答案 1 :(得分:0)
您还可以在扩展程序
中使用以下语法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)
}