将 C++ class 转换为另一个以创建 OpenCV 轨迹栏句柄

Casting C++ class into another one to create OpenCV trackbar handle

为了不弄乱全局变量和函数,我想使用 class 的函数作为 OpenCV 中轨迹栏句柄的函数。以下代码说明了这个想法:

void cam::set_Trackbarhandler(int i, void *func)
{
    /* This function might be called whenever a trackbar position is changed */
}

void cam::create_Trackbars(void)
{
    /**
     * create trackbars and insert them into main window.
     * 3 parameters are:
     * the address of the variable that is changing when the trackbar is moved,
     * the maximum value the trackbar can move,
     * and the function that is called whenever the trackbar is moved
     */

    const string trck_name = "Exposure";
    char wnd_name[128];
    get_Mainwindowname(wnd_name, sizeof(wnd_name));


    createTrackbar(trck_name, //Name of the trackbar
                    wnd_name, //Name of the parent window
                    &setting, //value that's changed
                    (int)out_max, //maximum value
                    this->set_Trackbarhandler); //pointer to the function that's called
}

我希望概述了它。编译时我得到的错误是

error: cannot convert 'cam::set_Trackbarhandler' from type 'void (cam::)(int, void*)' to type 'cv::TrackbarCallback {aka void (*)(int, void*)}'|

有没有办法将 void (cam::)(int, void*) 转换为简单的 void (*)(int, void*) 或者我必须使用全局函数,即

void set_Trackbarhandler(int i, void *func)

?如果我必须这样做,我最后的办法是使用 void 指针(参见 http://docs.opencv.org/modules/highgui/doc/user_interface.html)并发送一个指向 class 的指针,如

    createTrackbar(trck_name,
                    wnd_name,
                    &setting,
                    (int)out_max,
                    set_Trackbarhandler, //now a global function
                    this);

我猜。在 set_Trackbarhandler 函数中,我会像

这样进行转换
cam *ptr = static_cast<cam *>(func);

虽然听起来有点复杂。

嗯。您需要 一些 间接寻址,但这还不错...

class cam
{
public:

    void myhandler(int value)
    {
       // real work here, can use 'this'
    }

    static void onTrack(int value, void* ptr)
    {
        cam* c = (cam*)(ptr);
        c->myhandler(value);
    }
};

createTrackbar(trck_name,
                    wnd_name,
                    &setting,
                    (int)out_max,
                    cam::onTrack, //now a static member
                    this);