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

Objective-C Blocks, C++ Variables and async code

本文关键字:异步 代码 变量 c++ Objective-C      更新时间:2023-10-16

在iOS上将c++变量与obj-c异步代码粘合在一起时遇到问题。

真正的问题在async代码中,我使用的是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];
        });

Which give an error (Bad access), the problem is (I guess) the object is destroyed before the method runs, so I tried creating the object in the heap:


__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)];
        });

And still:


__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];
        });

I get keeping "Bad access" errors all the time

Any ideas ?

The __block qualifier tells the compiler to not copy the object for the block so that is why it is failing. If you are not reassigning mat or are not trying to prevent an unnecessary retain/copy operation then you should remove __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