0

我在将字符串与 UnsafeMutablePointers 相互转换时遇到问题。以下代码不起作用,返回错误的字符串。

// 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))

游乐场文件的链接在这里。如果有人有在 Swift 中使用 UnsafeMutablePointers 处理字符串的经验,我将非常感谢一些指导,因为我在过去几天没有取得任何进展。再次感谢!

4

1 回答 1

0

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

您将变量bytes本身的地址传递给函数,因此您看到的是用于表示该指针的字节。

你可能想要的是

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

将指针传递给数据字节。

您还应该考虑NSUTF8StringEncoding改用,因为转换为 NSASCIIStringEncoding可能会失败。

于 2015-08-11T07:22:34.563 回答