Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to UnsafePointer<UInt8> and length

Tags:

string

swift

When I using NSOutputStream's write method

func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int

I don't know how to convert String to UnsafePointer<UInt8> and length

How can I do this in swift?

like image 979
Chen-Tsu Lin Avatar asked Aug 28 '14 17:08

Chen-Tsu Lin


3 Answers

You have to convert the string to UTF-8 data first

let string = "foo bar"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

and then write it to the output stream

let outputStream: NSOutputStream = ... // the stream that you want to write to
let bytesWritten = outputStream.write(UnsafePointer(data.bytes), maxLength: data.length)

The UnsafePointer() cast is necessary because data.bytes has the type UnsafePointer<Void>, and not UnsafePointer<UInt8> as expected by the write() method.


Update for Swift 3:

let string = "foo bar"
// Conversion to UTF-8 data (cannot fail):
let data = string.data(using: String.Encoding.utf8)! 

// Write to output stream:
let outputStream: NSOutputStream = ... // the stream that you want to write to
let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
like image 55
Martin R Avatar answered Nov 13 '22 20:11

Martin R


Here is how to do it in Swift 3. Run fine in Swift 4 too

extension String {

  func toPointer() -> UnsafePointer<UInt8>? {
    guard let data = self.data(using: String.Encoding.utf8) else { return nil }

    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count)
    let stream = OutputStream(toBuffer: buffer, capacity: data.count)

    stream.open()
    data.withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in
      stream.write(p, maxLength: data.count)
    })

    stream.close()

    return UnsafePointer<UInt8>(buffer)
  }
}

To convert from String to UnsafeMutablePointer<Int8>

let cString = strdup("Hello") // UnsafeMutablePointer<Int8>

To convert from UnsafeMutablePointer<Int8> to String

let string = String(cString: cString!) // String
like image 16
onmyway133 Avatar answered Nov 13 '22 20:11

onmyway133


Swift 4,

Convert String to NSString, then use NSString's methods.

let text = "Hello"
let pointer: UnsafePointer<Int8>? = NSString(string: text).utf8String
let length = NSString(string: text).length
like image 7
Jirui Avatar answered Nov 13 '22 20:11

Jirui