2023年2月23日 星期四

[C] Call back

範例參考如下:


#include <stdio.h>
#include <stdlib.h>
#include "memory.h"
#include <string.h>
typedef unsigned char   u8;
typedef unsigned short  u16;
typedef void (*CALLBACK) (void*);

typedef struct _Object
{
    CALLBACK cb;
}obj;

void FunA(void *pParam)
{
    char *str = (char*)pParam;
    printf("%s\n", str);
    printf("Here is FuncA\n\n\n");
}

void FunB(void *pParam)
{
    char *str = (char*)pParam;
    printf("%s\n", str);
    printf("Here is FuncB\n\n\n");
}

void RegisterCallBackFunction (obj *pObj , CALLBACK cb)
{
    pObj->cb = cb ;
    printf("CALLBACK cb:0x%x\n", cb);
    printf("pObj->cb:0x%x\n\n", pObj->cb);    
}

void ObjectCall(obj *pObj)
{
    pObj->cb("Callback Function Test\n");
}



int main()
{
    int input;

    /*1. We have two objects*/
    obj objA, objB ; 

    /*2. Register*/
    RegisterCallBackFunction(&objA,FunA);
    RegisterCallBackFunction(&objB,FunB);

    /*3. */
    do 
    {
        printf("*** Please Enter an number (1-2): ");
        scanf("%d", &input);
        printf("\n");
        
        switch (input)
        {
            case 1:
                ObjectCall(&objA);
                break;
            
            case 2:
                   ObjectCall(&objB);
                break;
            
            default:
                printf("Wrong input\n");
                break;
        }
        
    } while (input < 3);
        
    system("PAUSE");
    return 0;
}

沒有留言:

張貼留言