How to convert String to UnsafePointer and length

前端 未结 9 1115
萌比男神i
萌比男神i 2020-12-09 16:13

When I using NSOutputStream\'s write method

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


        
9条回答
  •  盖世英雄少女心
    2020-12-09 16:35

    An answer for people working in Swift 4 now. You can no longer get bytes from a Data object, you have to copy them into an UnsafeMutablePointer

    let helloWorld = "Hello World!"
    
    let data = helloWorld.data(using: String.Encoding.utf8, allowLossyConversion: false)!
    var dataMutablePointer = UnsafeMutablePointer.allocate(capacity: data.count)
    
    //Copies the bytes to the Mutable Pointer
    data.copyBytes(to: dataMutablePointer, count: data.count)
    
    //Cast to regular UnsafePointer
    let dataPointer = UnsafePointer(dataMutablePointer)
    
    //Your stream
    oStream.write(dataPointer, maxLength: data.count)
    

提交回复
热议问题