Convert C++ function pointer to c function pointer

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

    @Snps answer is perfect! But as @DXM mentioned it can hold only one callback. I've improved it a little, now it can keep many callbacks of the same type. It's a little bit strange, but works perfect:

     #include 
    
    template
    struct ActualType {
        typedef T type;
    };
    template
    struct ActualType {
        typedef typename ActualType::type type;
    };
    
    template
    struct Callback;
    
    template
    struct Callback {
        typedef Ret (*ret_cb)(Params...);
        template
        static Ret callback(Args ... args) {
            func(args...);
        }
    
        static ret_cb getCallback(std::function fn) {
            func = fn;
            return static_cast(Callback::callback);
        }
    
        static std::function func;
    
    };
    
    template
    std::function Callback::func;
    
    #define GETCB(ptrtype,callertype) Callback::type,__COUNTER__,callertype>::getCallback
    

    Now you can just do something like this:

    typedef void (cb_type)(uint8_t, uint8_t);
    class testfunc {
    public:
        void test(int x) {
            std::cout << "in testfunc.test " <

提交回复
热议问题