Ios 为什么我的应用程序在将CVImageBufferRef变量传递给其他类时会崩溃

Ios 为什么我的应用程序在将CVImageBufferRef变量传递给其他类时会崩溃,ios,Ios,我的项目是用Swift编写的,我试图用Objective-C重写它。应用程序在Swift中运行得很好,但在Objective-C中崩溃了。由于项目很复杂,我基于苹果的示例代码“SquareCam”编写了一个演示应用程序,使其变得简单。您可以从Github获取代码: 在iphone上使用Xcode(7.2)运行应用程序,通过点击工具栏中的segment控件将摄像头切换到前端,几秒钟后,应用程序将在此崩溃: - (void)run { while (1) { CVIm

我的项目是用Swift编写的,我试图用Objective-C重写它。应用程序在Swift中运行得很好,但在Objective-C中崩溃了。由于项目很复杂,我基于苹果的示例代码“SquareCam”编写了一个演示应用程序,使其变得简单。您可以从Github获取代码:

在iphone上使用Xcode(7.2)运行应用程序,通过点击工具栏中的segment控件将摄像头切换到前端,几秒钟后,应用程序将在此崩溃:

    - (void)run {
    while (1) {
        CVImageBufferRef a = [self getImageBuffer];
        CVPixelBufferLockBaseAddress(a, 0);
        sleep(1);
        NSLog(@"111111");
        CVPixelBufferUnlockBaseAddress(a, 0);// crash here
    }
}
该应用程序的工作原理如下:

(1) “SquareCamViewController.m”使用CMSampleBufferGetImageBuffer获取CVPixelBufferRef变量

`- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{   
    NSLog(@"captureOutput");
    // got an image
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);`
(2) 类测试的一个实例(很抱歉名称不好)将“pixelBuffer”设置为它自己的变量

CVPixelBufferRef pixelBuffer=CMSampleBufferGetImageBuffer(sampleBuffer); [t setImageBuffer:pixelBuffer]//将“像素缓冲区”设置为自身

(3) 同时,类测试(test.m)正在另一个线程(队列)中运行,并尝试获取“CVImageBufferRef”变量,并调用CVPixelBufferLockBaseAddress和CVPixelBufferUnlockBaseAddress进行进一步处理

    - (void)run {
    while (1) {
        CVImageBufferRef a = [self getImageBuffer];
        CVPixelBufferLockBaseAddress(a, 0);
        sleep(1);
        NSLog(@"111111");
        CVPixelBufferUnlockBaseAddress(a, 0); // crash here
    }
}
在我最初的项目中,它崩溃得更快:

    void CVImageBufferRef_to_cvGRAY(CVImageBufferRef imgBuf, cv::Mat &imgOut)
{
// lock the buffer
    CVPixelBufferLockBaseAddress(imgBuf, 0); // maybe crash here

    // get the address to the image data
    void *imgBufAddr = CVPixelBufferGetBaseAddressOfPlane(imgBuf, 0);

    // get image properties
    int w = (int)CVPixelBufferGetWidth(imgBuf);
    int h = (int)CVPixelBufferGetHeight(imgBuf);

    cv::Mat mColor(h, w, CV_8UC4, (void*)imgBufAddr);
    cv::cvtColor(mColor, (imgOut), COLOR_BGRA2GRAY); // maybe crash here
    // unlock again
    CVPixelBufferUnlockBaseAddress(imgBuf, 0);
    mColor.~Mat();

}
我花了几天时间来处理这个问题,但我不知道如何解决这个问题,是关于多线程的吗?为什么Swift代码运行和Objective-C崩溃



有人能帮我吗?非常感谢。

可能您及时运行了此函数的多个实例,或者相机捕获覆盖了缓冲区,请添加一些检查以避免多次运行和覆盖可能您及时运行了此函数的多个实例,或者相机捕获覆盖了缓冲区,请添加一些检查以避免多次运行和覆盖