Ios 从VTCompressionOutputCallback中引用“self”
我目前正试图使用VideoToolbox对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
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
活动的情况下,它可能会在调用回调之前被释放。你会得到一个悬空的指针。