How to convert String to UnsafePointer and length

前端 未结 9 1063
萌比男神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:31

    You can also let Swift do it for you!

    import Foundation
    
    // Example function:
    func printUTF8Vals(_ ptr: UnsafePointer<UInt8>, _ len: Int) { 
        for i in 0..<len { 
            print(ptr[i]) 
        } 
    } 
    
    // Call it:
    let str = "Hello"
    printUTF8Vals(str, str.lengthOfBytes(using: String.Encoding.utf8))
    
    // Prints:
    // 72
    // 101
    // 108
    // 108
    // 111
    
    0 讨论(0)
  • 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<UInt8>.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<UInt8>(dataMutablePointer)
    
    //Your stream
    oStream.write(dataPointer, maxLength: data.count)
    
    0 讨论(0)
  • 2020-12-09 16:39

    By far the easiest way (in Swift 5):

    let s = "hello, world"
    let pointer = UnsafePointer(Array(s.utf8CString))
    

    Not sure how backwards compatible this is.

    0 讨论(0)
提交回复
热议问题