美文网首页
c语言callback

c语言callback

作者: help_youself | 来源:发表于2019-04-24 11:43 被阅读0次
    #include <stdio.h>
    typedef enum{
        MY_CAHR=1<<0,
        MY_INT=1<<1,
        MY_FLAOT=1<<2,
        MY_DOUBLE=1<<3,
        MY_PTR_OWN=1<<4,
        MY_PTR_NOWN=1<<5,
    }DataType;
    typedef struct{
        DataType type;
        union{
        char c;
        char *c_ptr;
        int b;
        float f;
        double d;
        void *ptr;
        };
    }MyValue;
    typedef void (*void_char_cast)(char,void*usr);
    typedef void (*void_ptr_cast)(void*,void*usr);
    typedef void (*CallbackTemplate)(void);
    typedef void (*ClousureTemplate)(CallbackTemplate cb,MyValue value,void *usr);
    void my_void_char_clousure(CallbackTemplate cb,MyValue value,void *usr){
        void_char_cast fn=(void_char_cast)(cb);
        fn(value.c,usr);
    }
    void my_void_ptr_clousure(CallbackTemplate cb,MyValue value,void *usr){
        void_ptr_cast fn=(void_ptr_cast)(cb);
        fn(value.ptr,usr);
    }
    typedef struct{
        ClousureTemplate tpl;
        CallbackTemplate cb;
        MyValue value;
        void *usr;
    }CallbackWrap;
    void test_char_fun(char c,void *usr){
        printf("%c\n",c);
    }
    void test_ptr_fun(void *ptr,void *usr){
        printf("%p\n",ptr);
    }
    void invoke_fun(CallbackWrap *fun){
        fun->tpl(fun->cb,fun->value,fun->usr);
    }
    int main(){
        CallbackWrap wrap={
            .tpl=my_void_char_clousure,
            .cb=test_char_fun,
            .value.c='a',
            .usr=0,
        };
        invoke_fun(&wrap);
        int a=1234;
       CallbackWrap wrap1={
            .tpl=my_void_ptr_clousure,
            .cb=test_ptr_fun,
            .value.ptr=(void*)&a,
            .usr=0,
        };
        invoke_fun(&wrap1);
    }
    
    

    相关文章

      网友评论

          本文标题:c语言callback

          本文链接:https://www.haomeiwen.com/subject/mngwgqtx.html