在 Swift 中使用 UnsafeMutablePointer 编码和解码字符串
Encoding and Decoding Strings using UnsafeMutablePointer in Swift
我在将字符串与 UnsafeMutablePointer 相互转换时遇到问题。以下代码不起作用,返回了错误的字符串。
// 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))
playground 文件的 link 是 here。如果有人在 Swift 中对字符串使用 UnsafeMutablePointers 有经验,我将非常感谢一些指导,因为我在过去几天没有取得任何进展。再次感谢!
有
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
可能会失败。
我在将字符串与 UnsafeMutablePointer 相互转换时遇到问题。以下代码不起作用,返回了错误的字符串。
// 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))
playground 文件的 link 是 here。如果有人在 Swift 中对字符串使用 UnsafeMutablePointers 有经验,我将非常感谢一些指导,因为我在过去几天没有取得任何进展。再次感谢!
有
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
可能会失败。