在swift3中使用字节

时间:2016-11-25 08:55:43

标签: swift unsafe-pointers

float *vertexBuffer = (float *)positionSource.data.bytes;
  

'字节'不可用:改为使用withUnsafeBytes

但我不知道如何使用它

_ = positionSource?.data.withUnsafeBytes({ (<#UnsafePointer<ContentType>#>) -> ResultType in

   })

2 个答案:

答案 0 :(得分:1)

我认为你可以这样做。

let str = "hello"
let strData = str.data(using: String.Encoding.utf8)!
strData.withUnsafeBytes { (bytes: UnsafePointer<CChar>) -> Void in
          print("\(bytes[1])")  //exp: access as c string
}

希望能帮到你!

答案 1 :(得分:0)

withUnsafeBytes是一种通用方法,推断出ContentType 从封闭的类型。与

data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) in
    // Use  vertexBuffer ...
}

你会得到UnsafePointer<Float>指向数据中的字节。 请注意,不得在闭包之外使用此指针。

您还可以计算结果并将其从闭包中传回 给来电者。例如:

let result = data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) -> Float in
    let result = // ... compute result ...
    return result
}