0

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

Community
  • 1
  • 1
nacho4d
  • 43,720
  • 45
  • 157
  • 240
  • 1
    nacho4d: I've already given a similar answer to your other question regarding this, but here's a link to a more detailed answer about how to do C callbacks with `void*` as user data from C++: http://stackoverflow.com/questions/3725425/class-method-as-winapi-callback/3725440#3725440 – sbi Sep 22 '10 at 07:38

1 Answers1

1

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
  • 24,777
  • 4
  • 73
  • 129
  • 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 Sep 22 '10 at 07:48