Swift 3 UnsafeMutablePointer初始化C类型float **

时间:2016-10-19 10:07:53

标签: c swift3 unsafemutablepointer

在Swift 3中,我需要将数据发送到接受float **输入的C对象。

在Swift 2中,我曾经声明一个UnsafeMutablePointer< UnsafeMutablePointer<Float32>>,构造一个swift数组(仅用于init!),然后将它传递给指针,它起作用了:

    var bufferOut: UnsafeMutablePointer< UnsafeMutablePointer<Float32>>?
    arrayOut = Array(repeating: Array(repeating: 0, count: Int(size1), count: Int(size2))
    bufferOut = UnsafeMutablePointer< UnsafeMutablePointer<Float32>>(arrayOut)

现在在Swift 3中已经破了!

  • 传递C风格float**并初始化它的最快捷方式是什么?
  • UnsafeMutablePointer< UnsafeMutablePointer<T>>中分配值的最佳方法是什么?

文档说明对于T **,应该使用AutoreleasingUnsafeMutablePointer<T>,但实际上我从未设法构建过一个!

请注意,我并不真正关心上面示例中的数组!如果我可以直接使用已知容量初始化指针,我会的。

注意Expected use cases Section of UnsafeRawPointer描述了有用的情况,例如C数组和C缓冲区,但是为上述结构翻译这些方法并不明显!

1 个答案:

答案 0 :(得分:2)

这是我最终做的并且正在工作。它遵循new UnsafeMuTablePointer Reference中关于简单方案的示例程序的建议。总之,需要分配从顶层开始分配每个插槽!

因此,为了构造一个UnsafeMutablePointer< UnsafeMutablePointer<T>>大小(size1,size2)(就像一个矩阵),你可以使用一个名为vectorBuf的中间向量,如下所示:

    var vectorBuf : UnsafeMutablePointer<T>?
    vectorBuf = UnsafeMutablePointer<T>.allocate(capacity: size2)
    for index in 0...(size2) {     // had Int(channelCount)*
        vectorBuf!.advanced(by: index).pointee = 0.0
    }

    /// This is where allocation and initialization happens:
    bufferOut = UnsafeMutablePointer< UnsafeMutablePointer<T>?>.allocate(capacity: Int(size1))
    for index in 0...Int(size1) {
        bufferOut!.advanced(by: index).pointee = UnsafeMutablePointer<T>.allocate(capacity: (size2) )
        bufferOut!.advanced(by: index).pointee?.assign(from: vectorBuf!, count: size2)
    }

希望这对于尝试在C / C ++中使用swift信号处理调用的其他人来说非常有用!