Convert C++ function pointer to c function pointer

后端 未结 7 1117
无人共我
无人共我 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:22

    @Snps answer is great. I extended it with a maker function that creates a callback, as I always use void callbacks without parameters:

    typedef void (*voidCCallback)();
    template
    voidCCallback makeCCallback(void (T::*method)(),T* r){
      Callback::func = std::bind(method, r);
      void (*c_function_pointer)() = static_cast(Callback::callback);
      return c_function_pointer;
    }
    

    From then on, you can create your plain C callback from within the class or anywhere else and have the member called:

    voidCCallback callback = makeCCallback(&Foo::print, this);
    plainOldCFunction(callback);
    

提交回复
热议问题