有没有办法在低级 C 方法调用中使用 Swift 命令?

Is there a way to utilize Swift commands within a low-level C method call?

我正在维护从 AVCaptureSynchronizedData 获得的一组数据。我使用的一种方法修改了从 AVCaptureSynchronizedData 获得的 CVPixelBuffers。修改的时候。 CVPixelBuffer,我通过

创建了 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))
    }
}

我收到错误

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

不确定这是否可能,但如果能够记录指针被销毁的次数将非常有用

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

How to use instance method as callback for function which takes only func or literal closure 类似,您必须使用自定义指针(此处: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)到空指针并返回到实例指针(此处:mySelf)的转换,请参阅