0

我正在维护一组从AVCaptureSynchronizedData. 我使用的一种方法修改了CVPixelBuffersAVCaptureSynchronizedData. 修改时。,我创建了一个viaCVPixelBuffer的副本CVPixelBuffer

let status = CVPixelBufferCreateWithBytes(nil, scaleWidth, scaleHeight,
                                                  pixelFormat, destData,
                                                  destBytesPerRow, releaseCallback,
                                                  nil, nil, &dstPixelBuffer)

releaseCallBack引用为

let releaseCallback: CVPixelBufferReleaseBytesCallback = { _, ptr in
    if let ptr = ptr {
        free(UnsafeMutableRawPointer(mutating: ptr))
    }
}

但是,我希望能够跟上这被调用的次数。但是,如果我添加类似

var num:Int = 0
let releaseCallback: CVPixelBufferReleaseBytesCallback = { _, ptr in
    if let ptr = ptr {
        num += 1
        free(UnsafeMutableRawPointer(mutating: ptr))
    }
}

我得到错误

AC 函数指针不能由捕获上下文的闭包形成

不确定是否可能,但是能够计算指针被销毁的次数将非常有用

4

1 回答 1

1

在闭包中引用实例变量num会捕获self,而这在纯 C 函数的回调中是不可能的。

与如何使用实例方法作为仅采用 func 或文字闭包的函数的回调类似,您必须使用自定义指针(此处:)releaseRefCon可以传递给回调:

let releaseCallback: CVPixelBufferReleaseBytesCallback = { releaseRefCon, ptr in
    let mySelf = Unmanaged<YourClass>.fromOpaque(releaseRefCon!).takeUnretainedValue()
    if let ptr = ptr {
        free(UnsafeMutableRawPointer(mutating: ptr))
        mySelf.num += 1
    }
}

let releaseRefCon = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
let status = CVPixelBufferCreateWithBytes(nil, scaleWidth, scaleHeight,
                                          pixelFormat, destData,
                                          destBytesPerRow,
                                          releaseCallback, releaseRefCon,
                                          nil, &dstPixelBuffer)

有关从实例指针(此处:)self到 void 指针并返回到实例指针(此处:)的转换,mySelf请参阅如何将 self 转换为 swift 中的 UnsafeMutablePointer<Void> 类型

于 2020-03-11T17:52:16.563 回答