从 VTCompressionOutputCallback 中引用“self”

Referencing `self` from within a VTCompressionOutputCallback

我目前正在尝试使用 VideoToolbox 对来自 AVCaptureVideoDataOutput 的视频数据进行编码,但我在从 VTCompressionOutputCallback.[=18 中引用 self 时遇到问题=]

我的代码如下:

...

var sessionRef: VTCompressionSession?

let outputCallback: VTCompressionOutputCallback = { _, _, status, _, sampleBuffer in
    guard status == noErr, let sampleBuffer = sampleBuffer else {
        return
    }

    debugPrint("[INFO]: outputCallback: sampleBuffer: \(sampleBuffer)")
}

let sessionErr = VTCompressionSessionCreate(allocator: nil,
                                            width: width,
                                            height: height,
                                            codecType: kCMVideoCodecType_H264,
                                            encoderSpecification: nil,
                                            imageBufferAttributes: nil,
                                            compressedDataAllocator: nil,
                                            outputCallback: outputCallback,
                                            refcon: nil,
                                            compressionSessionOut: UnsafeMutablePointer(&sessionRef))

...

工作正常,打印输出符合预期,但是当我尝试在 VTCompressionOutputCallback 中添加对 self 的引用时,它会收到一个编译器错误,指出

A C function pointer cannot be formed from a closure that captures context

如何在回调中使用 self

在此先感谢您的帮助。

我想出了解决办法。

VTCompressionSessionCreate 调用有一个用于 outputCallbackRefCon 的参数,它被传递给 VTCompressionOutputCallback

通过像这样 UnsafeMutableRawPointer 包裹自己

let unmanagedSelf = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())

我能够将该值传递到 refcon 参数下的 VTCompressionSessionCreate 中。在回调内部,我可以使用

将该值拉回
let scopedSelf = Unmanaged<ViewController>.fromOpaque(unmanagedSelf).takeUnretainedValue()