无法理解 withUnsafeBytes 方法的工作原理
Unable to understand how withUnsafeBytes method works
我正在尝试将 Data 转换为 UnsafePointer。我找到了一个答案 ,我可以在其中使用 withUnsafeBytes 来获取字节。
然后我自己做了一个小测试,看看我是否可以打印出字符串的字节值 "abc"
let testData: Data = "abc".data(using: String.Encoding.utf8)!
testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes.pointee)")
})
但是输出的只是一个字符的值,即"a".
2018-07-11 14:40:32.910268+0800 SwiftTest[44249:651107] 97
那我怎么才能得到所有三个字符的字节值呢?
"pointer"指向序列中第一个字节的地址。如果想得到指向其他字节的指针,就得用指针运算,即把指针移到下一个地址:
testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes.pointee)")
NSLog("\(bytes.successor().pointee)")
NSLog("\(bytes.advanced(by: 2).pointee)")
}
或
testData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes[0])")
NSLog("\(bytes[1])")
NSLog("\(bytes[2])")
}
但是,一定要注意testData
的字节大小,不要溢出
您得到“97”是因为 'bytes' 指向 'testdata' 的起始地址。
您可以获得所有三个字符的字节值或 n 个字符,如以下代码所示:
let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in
for idx in 0..<testData.count {
NSLog("\(bytes[idx])")
}
})
我正在尝试将 Data 转换为 UnsafePointer。我找到了一个答案
然后我自己做了一个小测试,看看我是否可以打印出字符串的字节值 "abc"
let testData: Data = "abc".data(using: String.Encoding.utf8)!
testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes.pointee)")
})
但是输出的只是一个字符的值,即"a".
2018-07-11 14:40:32.910268+0800 SwiftTest[44249:651107] 97
那我怎么才能得到所有三个字符的字节值呢?
"pointer"指向序列中第一个字节的地址。如果想得到指向其他字节的指针,就得用指针运算,即把指针移到下一个地址:
testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes.pointee)")
NSLog("\(bytes.successor().pointee)")
NSLog("\(bytes.advanced(by: 2).pointee)")
}
或
testData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes[0])")
NSLog("\(bytes[1])")
NSLog("\(bytes[2])")
}
但是,一定要注意testData
的字节大小,不要溢出
您得到“97”是因为 'bytes' 指向 'testdata' 的起始地址。
您可以获得所有三个字符的字节值或 n 个字符,如以下代码所示:
let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in
for idx in 0..<testData.count {
NSLog("\(bytes[idx])")
}
})