gpt4 book ai didi

swift - 将指针从 Swift 2 转换为 Swift 3

转载 作者:行者123 更新时间:2023-11-28 06:24:32 25 4
gpt4 key购买 nike

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

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

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

// Create result
var result = [Double](repeating: 0.0, count: N/2)
var resultAsComplex : UnsafeMutablePointer<DSPDoubleComplex>?
result.withUnsafeMutableBytes {
resultAsComplex = $0.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

最佳答案

你必须“重新绑定(bind)”指针:

values.withUnsafeMutableBufferPointer {
$0.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 {
$0.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 {
$0.baseAddress!.withMemoryRebound(to: DSPDoubleComplex.self, capacity: result.count/2) {
resultAsComplex in

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

}
}

关于swift - 将指针从 Swift 2 转换为 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42377367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com