string - 为什么将字符串指针转换为void指针然后返回会导致字符串数据消失? (Opencv

我正在尝试创建一个函数,该函数在一个地方初始化每个OpenCV窗口的所有鼠标处理程序。该代码在主循环中起作用,但在我的函数中不起作用(是的,我通过引用传递)。
问题似乎源于将指针传递给字符串-当出现另一端时,它将无法成功取消引用(*)。是什么赋予了?

这是我正在谈论的极简示例(它为两个相同的窗口设置了鼠标处理程序-一个窗口起作用,另一个窗口不起作用):

// mouse problem.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <string.h>
#include <iostream>  //for cout, cin

using namespace std;
using namespace cv;

void onMouse(int event, int x, int y, int flags, void* param){ 

    string windowname = *((string*)param);  //just recasting the void* we passed into the mousehandler to string
    if(windowname.empty()){
        cout << "ERROR.";
    }else{
        cout << "SUCCESS for window:" << windowname;
    }
    cout <<  "  param: "<< param << " windowname: "<< windowname << "\n";
}

void initializer(const string& name){
        namedWindow( name, CV_WINDOW_AUTOSIZE );
        cout << " initializing mouse handler for " << name << " with string at address :" << &name << "\n";
        setMouseCallback(name, onMouse, (void*)&name);  //this line is exactly the same as the other setmousecallback line
}

int _tmain(int argc, _TCHAR* argv[]){
    string name; Mat src; VideoCapture cap(0);  cap >> src; // get a single frame from camera

    //this works just fine
    name = "frameA";
    namedWindow( name, CV_WINDOW_AUTOSIZE );
    cout << " initializing mouse handler for " << name << " with string at address :" << &name << "\n";
    setMouseCallback(name, onMouse, (void*)&name);

    //this fails even though it contains the same code and we pass by reference
    initializer("frameB");

    imshow("frameA",src);   imshow("frameB",src);  //display frame - mouseing over them triggers the OnMouse() event
    while(true){  //loop forever
        waitKey(30);
    }
    return 0;
}

然后将iot_a悬停在每个窗口上一次。

如图所示,真正的杀死了我就是:成功识别了字符串的地址!并将其转换为字符串没有错误!但是当我取消引用它时,它说是空的!
是的,我确实尝试避免使用Void *。可悲的是,我无法避免空白。 OpenCV要求void是任何mousehandler函数的最后一个参数:(

最佳答案

问题与 Actor 表无关。您正在保留指向临时string对象的指针,并在对象超出范围后尝试取消对该指针的引用。

以下:

initializer("frameB");

等效于:
initializer(std::string("frameB"));

换句话说,将创建一个临时文件,并且该函数将获取并保留该临时文件的地址。由于临时语句在语句末尾消失,因此您留下了一个悬空的指针。

关于string - 为什么将字符串指针转换为void指针然后返回会导致字符串数据消失? (Opencv的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14090184/

相关文章:

c# - 使用 SURF 匹配 OpenCV\EmguCV 中的图像

python - opencv-python:不是一个numpy数组

matlab - 不裁剪的图像重映射

sql-server - 在 Azure Data Studio 中还原数据库备份时出现错误 "co

opencv - OPEN CV程序执行错误?

image-processing - 通过 find_contour 获取每个标志的 1 个轮廓并在

objective-c - iOS 中的 CVSurf (OpenCV) 功能

opencv - 密码本背景减法-一切都爆炸成白色

opencv - 使用Filestrage在OpenCV中保存和读取Mat向量的向量

opencv - Eclipse安装opencv 2.4.3库时出错