【问题标题】:Referencing `self` from within a VTCompressionOutputCallback [duplicate]从 VTCompressionOutputCallback 中引用`self` [重复]
【发布时间】:2019-03-29 15:47:48
【问题描述】:

我目前正在尝试使用 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 的引用,就会出现编译器错误提示

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

如何在回调中使用self?

提前感谢您的帮助。

【问题讨论】:

    标签: ios swift avfoundation video-toolbox


    【解决方案1】:

    我想出了一个解决办法。

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

    通过像这样将 self 包裹在 UnsafeMutableRawPointer 中

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

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

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

    【讨论】:

    • 您不应该在使用passRetained() 时传递self,并使用takeRetainedValue() 使用它,以便VTCompressionSessionCreate 具有保持self 存活的强引用吗?通过传递 unretained,在没有强引用保持 self 存活的情况下,它可能会在调用回调之前被释放。你会得到一个悬空指针。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多