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

'bytes' is unavailable: use withUnsafeBytes instead

but I don't know how to use it

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

   })
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
HaoDong
  • 339
  • 1
  • 10

2 Answers2

1

I think you can do it like this.

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
}

Hope to help you!

FlyingPuPu
  • 86
  • 2
0

withUnsafeBytes is a generic method, the ContentType is inferred from the type of the closure. With

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

you'll get a UnsafePointer<Float> pointing to the bytes in the data. Note that this pointer must not be used outside of the closure.

You can also compute a result and pass it back from the closure to the caller. Example:

let result = data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) -> Float in
    let result = // ... compute result ...
    return result
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382