获取视频流(CMSampleBufferRef)sampleBuffer的地址,并将其转为uint8_t/UInt8格式,Objective-C实现方式如下:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
//获取buffer
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
//获取buffer地址并强转
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
}
但Swift直接这样写:
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let imageBuffer: CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let baseAddress: UInt8 = CVPixelBufferGetBaseAddress(imageBuffer)! as UInt8
}
编译会报错:
Cannot convert value of type 'UnsafeMutableRawPointer' to type 'UInt8' in coercion
需要多转一步才可以:
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let imageBuffer: CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let tempPointer: UnsafeMutableRawPointer = CVPixelBufferGetBaseAddress(imageBuffer)!
let opaquePtr = OpaquePointer(tempPointer)
let baseAddress = UnsafeMutablePointer<UInt8>(opaquePtr)
}
以下资料参考# 在 Swift 里使用指针
Swift 一共有 8 种指针类型。基础是不可变指针 UnsafePointer,对应的会有可变指针 UnsafeMutablePointer。另外还有可以塞数组的 Buffer 指针和完全不知道是什么内容的 Raw 指针,也即没有指定泛型。
四种带类型指针:
UnsafeMutablePointer
UnsafePointer
UnsafeMutableBufferPointer
UnsafeBufferPointer四种不带类型的 RawPointer:
UnsafeMutableRawPointer
UnsafeRawPointer
UnsafeMutableRawBufferPointer
UnsafeRawBufferPointer
*Apple Developer 文档里有 C 指针和 Swift 指针的对应表:
C Syntax | Swift Syntax |
---|---|
const Type * | UnsafePointer |
Type * | UnsafeMutablePointer |
Type * const * | UnsafePointer |
Type * __strong * | UnsafeMutablePointer |
Type ** | AutoreleasingUnsafeMutablePointer |
const void * | UnsafeRawPointer |
void * | UnsafeMutableRawPointer |
CVPixelBufferGetBaseAddress
返回值为void *,对应Swift为UnsafeMutableRawPointer,而UnsafeMutableRawPointer不带任何类型,必须为它指一个类型,就要用到OpaquePointer
。