我想从String
创建Data
而不复制。我一直在尝试使用
String(bytesNoCopy:UnsafeMutableRawPointer, length:Int, encoding:String.Encoding, freeWhenDone:Bool)
无论我如何尝试,它总是返回零。如果我使用String(bytes:..., encoding:...)
创建它就会成功。
有没有办法尝试从String
对象创建Data
而不重复字节。
以下是它的来源和我尝试的内容:
...
// get the data. This succeeds
guard var data = try? Data(contentsOf: url, options: .mappedIfSafe) else {
return .failed
}
//Tried:
let ptr = UnsafeMutableRawPointer(&data)
let str = String(bytesNoCopy: ptr, length: data.count, encoding: .utf8, freeWhenDone: false)
答案 0 :(得分:0)
再次尝试,我发现了一种有效的方法:
...
// get the data. This succeeds
guard var data = try? Data(contentsOf: url, options: .mappedIfSafe) else {
return .failed
}
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in
let unsafePtr = UnsafeMutableRawPointer(ptr)
// This is now working
let str = String(bytesNoCopy: unsafePtr, length: data.count, encoding: .utf8, freeWhenDone: false)
}