从 Outsie it 范围 C++ 访问局部变量

access local variable from outsie it scope c++

本文关键字:访问 局部变量 C++ 范围 Outsie it      更新时间:2023-10-16

我有一个函数(trackObject),它有局部变量(posX和posY)。

在该函数中,有两个依赖于这两个变量的函数调用。(检查交叉点和检查命中)。

如果我编译程序,程序运行良好但滞后。

我想在 trackObject 之外调用这两个函数,但这两个局部变量无法访问。我想访问它,但我不知道如何访问。

我尝试将这些变量设为全局变量,但使这些变量全局化会使另一个变量(moments、moment10、moment01 和 area)也必须设置为全局变量。

但是当我这样做时,我会收到堆损坏异常。

有人知道怎么做吗?或者还有另一种解决方案?

这是我的代码

void trackObject(IplImage* imgThresh){
    // Calculate the moments of 'imgThresh'
    CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
    cvMoments(imgThresh, moments, 1);
    double moment10 = cvGetSpatialMoment(moments, 1, 0);
    double moment01 = cvGetSpatialMoment(moments, 0, 1);
    double area = cvGetCentralMoment(moments, 0, 0);
     // if the area<1000, I consider that the there are no object in the image and it's because of the noise, the area is not zero 
    if(area>1000){
        // calculate the position of the ball
        int posX = moment10/area;
        int posY = moment01/area;        
       if(lastX>=0 && lastY>=0 && posX>=0 && posY>=0)
        {
            // Draw a yellow line from the previous point to the current point
            cvLine(imgTracking, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,0,255), 4);
        }
        checkIntersection(300, lastY, posY);
        checkHit(posX,posY,lastX,lastY,startLineX, startLineY, endLineX, endLineY);
        lastX = posX;
        lastY = posY;
    }
    cvLine(imgTracking,cv::Point(100,300) , cv::Point(600,300),cv::Scalar(0,200,0),2,8);
    cvLine(imgTracking,cv::Point(100,400) , cv::Point(168,400),cv::Scalar(255,0,122),8,8);
    cvLine(imgTracking,cv::Point(171,400) , cv::Point(239,400),cv::Scalar(255,0,122),8,8);
    cvLine(imgTracking,cv::Point(241,400) , cv::Point(309,400),cv::Scalar(255,0,122),8,8);
    cvLine(imgTracking,cv::Point(312,400) , cv::Point(380,400),cv::Scalar(255,0,122),8,8);
    cvLine(imgTracking,cv::Point(383,400) , cv::Point(451,400),cv::Scalar(255,0,122),8,8);
    cvLine(imgTracking,cv::Point(454,400) , cv::Point(522,400),cv::Scalar(255,0,122),8,8);
    cvLine(imgTracking,cv::Point(525,400) , cv::Point(600,400),cv::Scalar(255,0,122),8,8);
    free(moments); 
}

使用指针将它们复制到调用函数的变量中:

void trackObject(IplImage* imgThresh, int *pX, int *pY)
{
    ...
    *pX = moment10 / area;
    *pY = moment01 / area;
    ...
}

调用函数将需要一些int来存储这些值:

IplImage imgThresh;
int copyX, copyY;
trackObject(&imgThresh, &copyX, &copyY);

通过删除对 malloc() 和 free() 的调用来减少"滞后":

void trackObject(IplImage* imgThresh){
    CvMoments moments;
    cvMoments(imgThresh, &moments, 1);
    double moment10 = cvGetSpatialMoment(&moments, 1, 0);
    double moment01 = cvGetSpatialMoment(&moments, 0, 1);
    double area = cvGetCentralMoment(&moments, 0, 0);
    //...

请注意 CvMoments 局部变量的声明,然后只需要将此局部变量的地址传递给需要指向 CvMoments 的指针的函数。

如果您遇到性能问题,可能是由于以下行:

CvMoment = (CvMoments)

malloc(sizeof(CvMoments));

如果频繁调用trackObject(),则重复调用malloc成本很高。