如何获得指向数字变量的指针?例如。转换得到UnsafePointer<UInt8>
指向包含Swift Int
的存储空间。我需要将Int
写入流。
我的例子:
public static func writeToOutputStream(text: String!, outputStream:NSOutputStream!){
let encodedDataArray = [UInt8](text.utf8)
//send length of the data so the server knows when the message ends.
outputStream.write(encodedDataArray.count, maxLength: 4)
outputStream.write(encodedDataArray, maxLength: encodedDataArray.count)
}
如果我想发送数据长度,我需要encodedDataArray.count
成为UnsafePointer<UInt8>
。
答案 0 :(得分:4)
使用withUnsafePointer
,如下所示:
let outputStream = NSOutputStream(toMemory: ())
outputStream.open()
var count: Int = 0x01020304 // = encodedDataArray.count in your program
withUnsafePointer(&count) { (pointer: UnsafePointer<Int>) -> Void in
outputStream.write(UnsafePointer<UInt8>(pointer), maxLength: 4)
}
outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey)
结果:
<04030201>
请注意,它将以little-endian顺序写入字节(因为Swift当前运行的所有平台都是little-endian)。如果您想用big-endian编写,请使用encodedDataArray.count.bigEndian
。