【问题标题】:Using bytes in swift3在 swift3 中使用字节
【发布时间】:2016-11-25 08:55:42
【问题描述】:
float *vertexBuffer = (float *)positionSource.data.bytes;

'bytes' 不可用:改用 withUnsafeBytes

但是不知道怎么用

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

   })

【问题讨论】:

  • positionSource是什么类型,它的内容是什么?
  • let positionSource = sphereNode.geometry?.getGeometrySources(for: .vertex)[0]

标签: swift unsafe-pointers


【解决方案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
}

希望能帮到你!

【讨论】:

    【解决方案2】:

    withUnsafeBytes 是一个泛型方法,ContentType 是推断出来的 从闭包的类型。与

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

    你会得到一个UnsafePointer&lt;Float&gt; 指向数据中的字节。 请注意,此指针不得在闭包之外使用。

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

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

    【讨论】:

    • 如果我想在闭包之外使用vertexBuffer怎么办?我想保持代码干净。
    • @JohnAstion: Data 仅在闭包环境中提供对其字节的访问。您的“清洁度”问题是什么?
    • 收到,谢谢!
    猜你喜欢
    • 2017-01-21
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多