将指针元组转换为指针指针

时间:2017-05-26 12:43:56

标签: swift ffmpeg libav

我有一段C代码:

#define AV_NUM_DATA_POINTERS 8
uint8_t *data[AV_NUM_DATA_POINTERS];

在swift生成的界面中,这看起来像:

var data: (UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?)

有一个需要此data变量的函数。它在C中的表示如下:

int sws_scale(..., const uint8_t *const srcSlice[], ...);

然而,swift会产生以下签名:

func sws_scale(..., _ srcSlice: UnsafePointer<UnsafePointer<UInt8>?>!, ...) -> Int32

将大元组转换为适用于sws_scale函数的类型的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

来自Swift.org - UnsafeRawPointer Migration的示例:

var bytes: (CChar, CChar, CChar, CChar) = (0x61, 0x62, 0x63, 0)
let name: String = withUnsafePointer(to: &bytes) { ptr -> String in
   return String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}

应用于sws_scale

var data: (UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?, UnsafeMutablePointer<UInt8>?)
withUnsafePointer(to: data) { dataPointer in
   let dataPointer =
      UnsafeRawPointer(dataPointer)
         .assumingMemoryBound(to: UnsafePointer<UInt8>?.self)

   sws_scale(…, dataPointer, …)
}

请勿执行以下操作:

withUnsafePointer(to: &data.0)

在优化的版本中使用上述代码时,我遇到了内存对齐问题。