dimanche 22 juillet 2018

How to successfully pass a functional object (or lambda) to the trackbar callback second argument (void*)?

I have a member function in my class:

void handler(int pos, cv::Mat &image);

and have a member callback function for createTrackbar:

static void on_trackbar(int pos, void* ptr);

Then I create this functional object in another member function:

std::function<void(int)> bind_handler = std::bind(static_cast<void (my_class::*)(int, cv::Mat&)>(&my_class::handler), this, std::placeholders::_1, img_threshold);
slider = 0;
cv::namedWindow("Test Filter", 1);
cv::createTrackbar("threshold", "Test Filter", &slider, 255, on_trackbar, (void*)&bind_handler);

Then in on_trackbar I catch the void* ptr:

std::function<void(int)>* cb = static_cast<std::function<void(int)>* >(ptr);
(*cb)(pos); //<-- segfault

Compiled OK.

But when I touch the slider it goes to segmentation fault :(

Also I tried this code with lambdas but it segfaults too.

If I take std::shared_ptr<cv::Mat> thrsh_ptr to handler lambda by [=] it segfaults too.

How to make it correctly?

Aucun commentaire:

Enregistrer un commentaire