【问题标题】:Idiomatic way in Swift to typecast an UnsafeMutablePointer<Void> to an Array of non-void types?Swift 中将 UnsafeMutablePointer<Void> 类型转换为非 void 类型数组的惯用方式?
【发布时间】:2016-07-10 23:26:12
【问题描述】:

许多 C/Obj-C API 处理指向 void 的指针。在 swift 中,这些类型通常表示为 UnsafeMutablePointer 或 UnsafePointer(对于 const void*)。 Swift 中将这些值重新解释为压缩数据数组的典型方法是什么,例如 [Float] 或 [UInt8]?

【问题讨论】:

  • 你可能想添加一个用例,这个问题太笼统了。例如。为什么要将它们转换为数组?
  • 具体场景是使用MTLBuffer.contents(),它返回UnsafePointer,因为就API而言数据只是一个比特包。调用代码知道正确的解释,但需要相应地重新解释类型以便自然地访问它。

标签: swift unsafe-pointers


【解决方案1】:

最简单的方法是将其转换为UInt8指针:

let buffer = UnsafeMutablePointer<UInt8>(MTLBuffer.contents())

您可以使用下标运算符访问它:

for index in 0 ..< bufferSize {
    let foo = buffer[index]      // foo is `UInt8` type
    ...
    buffer[index] = bar
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    相关资源
    最近更新 更多