将指针从 Swift 2 转换为 Swift 3

Convert pointers from Swift 2 to Swift 3

如何将以下指针初始化从 Swift 2 转换为 Swift 3?

var values: [Double]
...
var valuesAsComplex : UnsafeMutablePointer<DSPDoubleComplex>?
values.withUnsafeBufferPointer { (resultPointer: UnsafeBufferPointer<Double>) -> Void in
    valuesAsComplex = UnsafeMutablePointer<DSPDoubleComplex>( resultPointer.baseAddress )
}

更新: 感谢您的所有回答。 按照@Aderstedt 的建议永久重新绑定指针,但返回结果无效。有什么想法吗?

// Create result
var result = [Double](repeating: 0.0, count: N/2)
var resultAsComplex : UnsafeMutablePointer<DSPDoubleComplex>?
result.withUnsafeMutableBytes {
    resultAsComplex = [=13=].baseAddress?.bindMemory(to: DSPDoubleComplex.self, capacity: result.count)
}

// Do complex->real inverse FFT.
vDSP_fft_zripD(fftSetup!, &tempSplitComplex, 1, LOG_N, FFTDirection(FFT_INVERSE));

// This leaves result in packed format. Here we unpack it into a real vector.
vDSP_ztocD(&tempSplitComplex, 1, resultAsComplex!, 2, N2);

// Neither the forward nor inverse FFT does any scaling. Here we compensate for that.
var scale : Double = 0.5/Double(N);
vDSP_vsmulD(&result, 1, &scale, &result, 1, vDSP_Length(N));

return result

你必须"rebind"指针:

values.withUnsafeMutableBufferPointer {
    [=10=].baseAddress!.withMemoryRebound(to: DSPDoubleComplex.self, capacity: values.count/2) {
        valuesAsComplex in

        // ...

    }
}

闭包内部 valuesAsComplex 是一个 UnsafeMutablePointer<DSPDoubleComplex> 并且可以传递给DSP 职能。

您必须将指向元素存储的指针传递给 在 documentation 明确声明的闭包之外:

The pointer argument is valid only for the duration of the closure’s execution.

这可能会偶然起作用,但不能保证在 执行闭包,元素存储还是一样 内存地址(或者数组甚至存在,因为指针 不是确保存储生命周期的强引用。


你的情况是

    tempSplitComplex = DSPDoubleSplitComplex(realp: &mag, imagp: &phase)
    vDSP_ztocD(&tempSplitComplex, 1, &tempComplex, 2, N2);

    tempComplex.withUnsafeMutableBufferPointer {
        [=11=].baseAddress!.withMemoryRebound(to: Double.self, capacity: values.count * 2) {
            complexAsDouble in

            vDSP_rectD(complexAsDouble, 2, complexAsDouble, 2, N2);
        }
    }

    vDSP_ctozD(&tempComplex, 2, &tempSplitComplex, 1, N2);

    var result = [Double](repeating: 0.0, count: N/2)

    result.withUnsafeMutableBufferPointer {
        [=12=].baseAddress!.withMemoryRebound(to: DSPDoubleComplex.self, capacity: result.count/2) {
            resultAsComplex in

            vDSP_ztocD(&tempSplitComplex, 1, resultAsComplex, 2, N2);

        }
    }