[英]Get UnsafePointer<UInt8> to Int to write an encoded Int to a stream
How do you get a pointer to a number variable? 如何获得指向数字变量的指针? Eg convert get an UnsafePointer<UInt8>
that points to the storage containing a Swift Int
. 例如,转换将获得一个UnsafePointer<UInt8>
,它指向包含Swift Int
的存储。 I need to write the Int
to a stream. 我需要将Int
写入流中。
My example: 我的例子:
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)
}
I need encodedDataArray.count
to be an UnsafePointer<UInt8>
if I want to send the data length too. 如果我也想发送数据长度,我需要encodedDataArray.count
是UnsafePointer<UInt8>
。
Use withUnsafePointer
, like this: 与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)
Result: 结果:
<04030201>
Note that it'll write the bytes in little-endian order (because all platforms on which Swift currently runs are little-endian). 请注意,它将以低字节序写入字节(因为当前运行Swift的所有平台都是低字节序)。 If you want to write in big-endian, use encodedDataArray.count.bigEndian
. 如果要使用big-endian编写,请使用encodedDataArray.count.bigEndian
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.