Convert C++ function pointer to c function pointer

后端 未结 7 1131
无人共我
无人共我 2020-12-01 04:42

I am developing a C++ application using a C library. I have to send a pointer to function to the C library.

This is my class:

 class MainWindow : pub         


        
7条回答
  •  广开言路
    2020-12-01 05:24

    The short answer is: you can convert a member function pointer to an ordinary C function pointer using std::mem_fn.

    That is the answer to the question as given, but this question seems to have a confused premise, as the asker expects C code to be able to call an instance method of MainWindow without having a MainWindow*, which is simply impossible.

    If you use mem_fn to cast MainWindow::on_btn_clicked to a C function pointer, then you still a function that takes a MainWindow* as its first argument.

    void (*window_callback)(MainWindow*,int*) = std::mem_fn(&MainWindow::on_btn_clicked);
    

    That is the answer to the question as given, but it doesn't match the interface. You would have to write a C function to wrap the call to a specific instance (after all, your C API code knows nothing about MainWindow or any specific instance of it):

    void window_button_click_wrapper(int* arg)
    {
        MainWindow::inst()->on_btn_clicked(arg);
    }
    

    This is considered an OO anti-pattern, but since the C API knows nothing about your object, it's the only way.

提交回复
热议问题