0

So I started to develope an OpenCV program and the thing is that I don't know what this segment of code do in the whole context. Below is an abstract version of the whole code.

class foo{
private:
    friend void callBack(void *param);
    void draw(void);
public:
    void func(void);
    void update(void);
}

void callBack(void *param){
    foo *context = static_cast<foo*>(param);
    if(context){
        context->draw();
    }
}

foo::foo(std::string windowName){
    cv::namedWindow(windowName, frameSize.width, frameSize.height);
    cv::resizeWindow(windowName, frameSize.width, frameSize.height);
    cv::setOpenGlContext(windowName);
    cv::setOpenGlDrawCallback(windowName, callBack, this);
}

void foo::func(void){
    cv::updateWindow(m_windowName);
}

void draw(void){
    //implementation shows here!!
}

You don't have to explain all the code here. All I need to know is the part where static casting happens. What does it do? Why does a person who implements the code write it this way?

BDL
  • 21,052
  • 22
  • 49
  • 55
Windforces
  • 313
  • 4
  • 12
  • 1
    That is the usual pattern to interface with a C-library callback mechanism. The callback is registered with a pointer to user data (which is the object pointer in this case) –  Jun 22 '16 at 12:46
  • I know what callback function is and how does it works. The thing I want to ask is the reason why they used static_cast param. Does this create new class and replace the one that has been existed? – Windforces Jun 22 '16 at 12:49

1 Answers1

3

As you can see from the documentation of cv::setOpenGlDrawCallback

The signature is:

void cv::setOpenGlDrawCallback(const String& winname,
                               OpenGlDrawCallback onOpenGlDraw,
                               void* userdata = 0 
                              )

The OpenGLDrawCallback is a function pointer of type void (void* arg): where arg is any pointer type you pass to it. In this case, OpenCV actually passes userdata to it. See How do function pointers in C work? (still applicable to C++)

cv::setOpenGlDrawCallback(windowName, callBack, this);

In your code, passing this implicitly converted (a copy of the pointer) it to void* and held by userdata . And and callback is called to draw on your frame

All I need to know is the part where static casting happens. What does it do? Why does a person who implements the code write it this way?

void callBack(void *param){
    foo *context = static_cast<foo*>(param);
    if(context){
        context->draw();
    }
}

The casting converts the void pointer, param to an object of type foo. it basically gets back the semantics of this that was casted when you passed it as a void pointer.

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68