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
. I need to write the Int
to a stream.
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.
Use withUnsafePointer
, like this:
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). If you want to write in big-endian, use encodedDataArray.count.bigEndian
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.