我试图编写一种方法来调整在Swift中捕获的图像的大小,但是在我的函数循环(实时捕获帧)中,捕获了几秒钟后发生了一个错误。我意识到我没有在分配内存,所以我添加了defer语句来执行此操作,但是这些defer语句抛出malloc错误,表明我尚未分配内存,但是我认为我已经正确分配了内存。因此,我无法释放正在分配的内存。
我尝试添加CVPixelBuffer(Un)LockBaseAddress语句,但是没有执行任何操作。
private func resizePixelBuffer(imageBuffer: CVPixelBuffer, scaleWidth: Int, scaleHeight: Int) -> CVPixelBuffer? {
CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
guard let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer) else {return nil}
let bytes_per_row = CVPixelBufferGetBytesPerRow(imageBuffer)
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
// Allocate input buffer
var inBuff = vImage_Buffer(data: baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: bytes_per_row)
defer { free(inBuff.data) } // ADDED
// Allocate output container
let outData = UnsafeMutablePointer<UInt8>.allocate(capacity: 4*scaleWidth*scaleHeight)
defer { outData.deallocate() } // ADDED
// Assign output buffer
var outBuff = vImage_Buffer(data: outData, height: vImagePixelCount(scaleHeight), width: vImagePixelCount(scaleWidth), rowBytes: 4*scaleWidth)
defer { free(outBuff.data) } // ADDED
let releaseCallback: CVPixelBufferReleaseBytesCallback = {_, ptr in
if let ptr = ptr {
free(UnsafeMutableRawPointer(mutating: ptr))
}
}
// Assign output data
let error = vImageScale_ARGB8888(&inBuff, &outBuff, nil, vImage_Flags(kvImageHighQualityResampling))
guard error == kvImageNoError else {return nil}
CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
...
}
python-ios-integration(2477,0x16cf5f000) malloc: *** error for object 0x10e84c000: pointer being freed was not allocated; python-ios-integration(2477,0x16cf5f000) malloc: *** set a breakpoint in malloc_error_break to debug