How to convert String to UnsafePointer and length

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

    I see there are other answers, and an accepted answer, so it seems you've gotten what you need. I came here because I noticed Swift 5's deprecation warnings for withUnsafeMutableBytes et al, and started testing @abdullahselek's answer, but I noticed in Swift 5 (haven't yet verified if it worked in previous versions) that String is convertible to UnsafePointer in-line, so you can use it in place where an UnsafePointer is expected. In case it helps to see another example, here's our old and updated function, posted here:

    OLD

    let derivationStatus = localDerivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in
      salt.withUnsafeBytes { saltBytes in
    
        CCKeyDerivationPBKDF(
          CCPBKDFAlgorithm(kCCPBKDF2),
          password,
          passwordData.count,
          saltBytes,
          salt.count,
          algorithm,
          UInt32(rounds),
          derivedKeyBytes,
          derivedKeyData.count
        )
      }
    }
    

    NEW

    let derivationStatus = localDerivedKeyData.withUnsafeMutableBytes { (outputBytes: UnsafeMutableRawBufferPointer) -> Int32 in
      let status = CCKeyDerivationPBKDF(
        CCPBKDFAlgorithm(kCCPBKDF2),
        password, // a String
        passwordData.count, // just the password String converted to Data
        String(data: salt, encoding: .utf8),  // converts salt (Data) to String
        salt.count,
        algorithm,
        UInt32(rounds),
        outputBytes.baseAddress?.assumingMemoryBound(to: UInt8.self),
        derivedKeyData.count
      )
      return status
    }
    

    With that said, you could use a similar approach to get your stream as follows:

    let stream = OutputStream(toBuffer: UnsafeMutablePointer(mutating: someString), capacity: someString.data(using: .utf8)!.count)
    

    (the ! is used to silence the compiler error, but you should avoid force-unwrapping where possible).

提交回复
热议问题