将数据转换为UnsafeMutablePointer <double>

时间:2019-05-03 02:08:35

标签: swift

我正在尝试将数据转换为UnsafeMutablePointer。 我遇到编译警告和问题。 感谢任何人急需的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以使用withUnsafeMutableBytesbindMemorybaseAddress。例如

// build sample `Data` with three `Double`

let foo = [1.0, 2.0, 3.0]
var data = foo.withUnsafeBytes { Data($0) }

// or, if a single value
//
// let foo = 42.0
// var data = withUnsafeBytes(of: foo) { Data($0) }

// print the hex representation

print(data as NSData)

// now convert the `Data` back to `Double`

data.withUnsafeMutableBytes { rawBufferPointer in
    let bufferPointer = rawBufferPointer.bindMemory(to: Double.self)

    // this is the `UnsafeMutablePointer<Double>`

    guard let pointer = bufferPointer.baseAddress else { return }
    print(pointer)

    // or, if you want the actually want the `Double` values, you can just iterate ...

    for value in bufferPointer {
        print(value)
    }

    // ... or you can use subscripts

    for i in 0 ..< bufferPointer.count {
        print(bufferPointer[i])
    }
}

不用说,此UnsafeMutableRawBufferPointerUnsafeMutableBufferPointer<Double>UnsafeMutablePointer<Double>仅应在此闭包内部使用。

曾经有一种withUnsafeMutableBytes的演绎形式直接检索了此UnsafeMutablePointer<T>,但已被弃用。但是您可以使用以上内容。

请注意,对于bindMemory,您必须确保:

  

必须将内存未初始化或初始化为与T布局兼容的类型。如果内存未初始化,则在绑定到T之后,它仍会初始化。

显然,上面的示例很好,但是很明显,如果没有更多有关如何以及为什么这样做的背景信息,我们就无法对您的案件发表评论。