tags:

views:

18

answers:

1

Hi, maybe this is the continuation of this thread,

The program compiles without errors or warnings but when I run it, and the handler function is called, I get EXEC_BAD_ADDRESS

void MainController::show_color_trackbars(int *h, int *s, int *v){
    String winName = "HSV Trackbars";
    namedWindow(winName, CV_WINDOW_AUTOSIZE);

    std::map<String, void*> user_data_h;
    user_data_h["Object"] = this; //this is a MainController object
    user_data_h["h"] = h;
    createTrackbar("trackbar_H", winName, h, 255, trackbar_handler, &user_data_h);

};

void trackbar_handler(int value, void *user_data){//callback for the track bar
    std::map <String, void*> *user_data_map;
    user_data_map = reinterpret_cast<std::map<String, void *> *>(user_data);

    MainController *controller;
    controller = reinterpret_cast<MainController *>((*user_data_map)["Object"]);

    int *var;
    var = reinterpret_cast<int*> ((*user_data_map)["h"]);

    //do something with controller and var
};

I am mistaking something when casting? I cannot think of another reason this code is failing.

Thanks in advance

+1  A: 

That's because in all probablity user_data_h is a local variable and is already destroyed when trackbar_handler is called. trackbar_handler works on a pointer which is no longer valid!

Please check if it is okay to have user_data_h dynamically allocated and register that pointer with the callback dispatch.

Chubsdad
I see. But then, I don't really understand the merit of this function. I believe is was not thought to be used in OOP. Reason: If I have to have a pointer which is valid it means it has to be a global or at least a member of my class (so I can release it later). And if I do this then there is no necessity of having void* user_data parameter in the function. I am correct?
nacho4d
Yes. You are right.
Chubsdad