Swift 是否管理我从 CVPixelBufferCreate 创建的 CVPixelBuffer 的内存?

问题描述 投票:0回答:1

假设我想存储相机输出的一帧

let imageBuffer:CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
some_list.append(imageBuffer.copy())

这是如何通过扩展 CVPixelBuffer 来定义复制函数

extension CVPixelBuffer {
    func copy() -> CVPixelBuffer {
        precondition(CFGetTypeID(self) == CVPixelBufferGetTypeID(), "copy() cannot be called on a non-CVPixelBuffer")
        var _copy : CVPixelBuffer?
        CVPixelBufferCreate(
            nil,
            CVPixelBufferGetWidth(self),
            CVPixelBufferGetHeight(self),
            CVPixelBufferGetPixelFormatType(self),
            CVBufferGetAttachments(self, CVAttachmentMode.shouldPropagate),
            &_copy)
        guard let copy = _copy else { fatalError() }
        CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags.readOnly)
        CVPixelBufferLockBaseAddress(copy, CVPixelBufferLockFlags(rawValue: 0))
        let dest = CVPixelBufferGetBaseAddress(copy)
        let source = CVPixelBufferGetBaseAddress(self)
        let height = CVPixelBufferGetHeight(self)
        let bytesPerRow = CVPixelBufferGetBytesPerRow(self)
        memcpy(dest, source, height * bytesPerRow)
        CVPixelBufferUnlockBaseAddress(copy, CVPixelBufferLockFlags(rawValue: 0))
        CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags.readOnly)
        return copy
    }
}

问题是:我是否需要显式管理我创建的 CVPixelBuffer 副本?或者 Swift 通过引用计数来处理它?

swift avfoundation avcapturesession
1个回答
5
投票

Swift 管理你的缓冲区对象,所以你不必考虑释放它。

从带注释的 API 返回的 Core Foundation 对象在 Swift 中自动进行内存管理 - 您无需自己调用 CFRetain、CFRelease 或 CFAutorelease 函数。

https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/working_with_core_foundation_types#2994152

事实上,

CVPixelBufferRelease
函数没有Swift版本。

https://developer.apple.com/documentation/corevideo/1563589-cvpixelbufferrelease

© www.soinside.com 2019 - 2024. All rights reserved.