Objective-C块,C ++变量和异步代码

时间:2011-12-07 18:26:06

标签: c++ objective-c asynchronous pass-by-reference objective-c-blocks

我在使用iOS上的obj-c异步代码粘合c ++变量时遇到了问题。

真正的问题在异步代码中,我使用的是用C ++构建的第三方库,它们期望引用对象,例如:


- (void) processFrame:(cv::Mat &)mat;

我的问题真正的问题是如何调用这个?我需要在不同的线程上创建c ++对象并将其传递给异步代码,有点像这样:


__block cv::Mat mat(videoRect.size.height, videoRect.size.width, CV_8UC4, baseaddress, 0);
dispatch_async(dispatch_get_main_queue(), ^{
            [self processFrame:mat];
        });

哪个给出错误(访问不良),问题是(我猜)在方法运行之前对象被销毁,所以我尝试在堆中创建对象:


__block cv::Mat *mat= new cv::Mat(videoRect.size.height, videoRect.size.width, CV_8UC4, baseaddress, 0);
dispatch_async(dispatch_get_main_queue(), ^{
            [self processFrame:(*mat)];
        });

仍然:


__block cv::Mat *mat= new cv::Mat(videoRect.size.height, videoRect.size.width, CV_8UC4, baseaddress, 0);
dispatch_async(dispatch_get_main_queue(), ^{
            [self processFrame:mat];
        });

我始终保持“错误访问”错误

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

__block限定符告诉编译器不要复制块的对象,这就是它失败的原因。如果您未重新分配mat或未尝试阻止不必要的保留/复制操作,则应删除__block

cv::Mat mat(videoRect.size.height, videoRect.size.width, CV_8UC4, baseaddress, 0);
dispatch_async(dispatch_get_main_queue(), ^{
            [self processFrame:mat];
        });

您创建new cv::Mat的示例可能会失败,因为您可能会过早删除mat

__block cv::Mat *mat= new cv::Mat(videoRect.size.height, videoRect.size.width, CV_8UC4, baseaddress, 0);
dispatch_async(dispatch_get_main_queue(), ^{
            [self processFrame:mat];
            //mat would need to be deleted here
        });
delete mat; //If you are doing this, you will likely get an EXC_BAD_ACCESS