Ask Your Question

Using shared_ptr/cv::Ptr as userdata in callbacks

asked 2018-11-01 07:47:49 -0500

vishal733 gravatar image

I am tracking mouse clicks inside an OpenCV display window by using:

void on_buttonClick(int event, int x, int y, int flags, void* userdata) 
    // Callback function received

void main() {
    cv::setMouseCallback(win_name, on_buttonClick, (void*) fun_ptr);

The last parameter fun_ptr is returned as part of user_data in the callback. And this is fine as long as I want to use function pointers for userdata.

But now I need to instead pass something equivalent of std::shared_ptr<CustomClass> as part of user_data. The reason I want to pass a shared_ptr is so that the object automatically get destroyed whenever the context of display window is refreshed.

I tried using two mechanisms:
- std::shared_ptr
- cv::Ptr (Similar in functionality to std::shared_ptr)

Example code below:

class CustomClass {
    int x;
    int y;

int main() {
    cv::Ptr<CustomClass> x(new CustomClass());
    cv::setMouseCallback(win_name, on_buttonClick, (void*) x);

But the shared_ptr would lose it's purpose as soon as I cast it to (void*). Is there a way to resolve this in OpenCV (afaik, using the typical new, delete would not be good since the time to delete cannot be ascertained).

edit retag flag offensive close merge delete


so that the object automatically get destroyed whenever the context of display window is refreshed.

that's a bit unclear, can you explain ?

berak gravatar imageberak ( 2018-11-01 08:17:00 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2018-11-01 07:56:14 -0500

berak gravatar image

those callbacks stem back from the c-api era, and don't have any notion of "smart" pointers.

idk, how "fictional" your example is, but you probably should not use new or delete at all here.

construct your struct in auto memory, and just pass the address of it,

it's all safe, as long as you do that inside main() (so the lifetime of the address passed to the callback does not exceed the life of the actual instance) , like:

int main() {
    CustomClass x;
    cv::setMouseCallback(win_name, on_buttonClick, (void*) &x);
edit flag offensive delete link more

Question Tools

1 follower


Asked: 2018-11-01 07:47:49 -0500

Seen: 240 times

Last updated: Nov 01 '18