为了不干扰全局变量和函数,我想在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)并将指向该类的指针作为发送回
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);