swiftcocoansstringnsstringencodingiobluetooth

Encoding and Decoding Strings using UnsafeMutablePointer in Swift


I'm having trouble converting strings to and from UnsafeMutablePointers. The following code doesn't work, returning the wrong string.

// func rfcommChannelData(rfcommChannel: IOBluetoothRFCOMMChannel!, data dataPointer: UnsafeMutablePointer<Void>, length dataLength: Int)
func receivingData(data dataPointer: UnsafeMutablePointer<Void>, length dataLength: Int) {
    let data = NSData(bytes: dataPointer, length: dataLength)
    println("str = \(NSString(data: data, encoding: NSASCIIStringEncoding))")
}

// - (IOReturn)writeSync:(void *)data length:(UInt16)length;
func sendingData(data: UnsafeMutablePointer<Void>, length: UInt16) {
    receivingData(data: data, length: Int(length))
}


var str: NSString = "Hello, playground"
var data = str.dataUsingEncoding(NSASCIIStringEncoding)!
var bytes = data.bytes

sendingData(&bytes, UInt16(data.length))

A link to the playground file is here. If anyone has experience using UnsafeMutablePointers in Swift for strings, I would very much appreciate some guidance as I have made no progress in the last few days. Thanks again!


Solution

  • With

    var bytes = data.bytes
    sendingData(&bytes, UInt16(data.length))
    

    you pass the address of the variable bytes itself to the function, so what you see is the bytes that are used to represent that pointer.

    What you probably want is

    let str = "Hello, playground"
    let data = str.dataUsingEncoding(NSASCIIStringEncoding)!
    sendingData(UnsafeMutablePointer(data.bytes), UInt16(data.length))
    

    to pass the pointer to the data bytes.

    You should also consider to use NSUTF8StringEncoding instead, because a conversion to NSASCIIStringEncoding can fail.