Ios 从VTCompressionOutputCallback中引用“self”

Ios 从VTCompressionOutputCallback中引用“self”,ios,swift,avfoundation,video-toolbox,Ios,Swift,Avfoundation,Video Toolbox,我目前正试图使用VideoToolbox对AVCaptureVideoDataOutput中的视频数据进行编码,但在VTCompressionOutputCallback中引用self时遇到问题 我的代码如下: ... var sessionRef: VTCompressionSession? let outputCallback: VTCompressionOutputCallback = { _, _, status, _, sampleBuffer in guard statu

我目前正试图使用VideoToolbox对
AVCaptureVideoDataOutput
中的视频数据进行编码,但在
VTCompressionOutputCallback
中引用
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
的引用,就会出现一个编译器错误

不能从捕获上下文的闭包中形成C函数指针

如何在回调中使用
self


提前感谢您的帮助。

我想出了一个解决方案

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

将self包装在一个
非女性化的指针中

let unmanagedSelf = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
我能够将该值传递到
refcon
参数下的
VTCompressionSessionCreate
。在回调内部,我可以使用

let scopedSelf = Unmanaged<ViewController>.fromOpaque(unmanagedSelf).takeUnretainedValue()
let scopedSelf=Unmanaged.from不透明(unmanagedSelf).takeUnrepainedValue()

您是否应该在使用
passRetained()
时传递
self
,并使用
takeRetainedValue()
来使用它,这样
VTCompressionSessionCreate
就有了一个强大的引用,保持
self
处于活动状态?通过未恢复的传递,在没有强引用保持
self
活动的情况下,它可能会在调用回调之前被释放。你会得到一个悬空的指针。