2015-02-09 18 views
1

爲了不混淆全局變量和函數,我想在OpenCV中使用類的函數作爲軌跡條句柄的函數。下面的代碼描述了一個思路:將C++類轉換爲另一個創建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) 

?如果非要那樣做,我的最後一招是使用空指針(見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); 

雖然聽起來有點複雜。

+1

您可以將指針不能轉換爲成員函數指針。如果您不想使用全局函數,請在名稱空間中聲明它。 – 2015-02-09 19:57:26

回答

3

好。你需要一些間接的,但它不是那麼糟糕......

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); 
+0

這很好。要強調第六個參數對createTrackbar()的重要性,它是靜態回調如何獲取實例的句柄。我沒有通過這個,並花了我五分鐘與gdb想知道爲什麼這不起作用。但唉:它的確如打字一樣。 – Jameson 2016-03-11 13:15:17