指針的妙用

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int *handle;
    int msg_type;
    int parm;
}message_t;

typedef void (* object_callback)(message_t *message);

typedef struct
{
    int *handle;
    int object_id;
    object_callback def_cb;
}object_t;

void msg_process(message_t * msg)
{
    switch(msg->msg_type)
    {
        case 0:
            printf("Hello type 0. \n");
            break;
        case 1:
            printf("Hello type 1. \n");
            break;
        default:
            printf("msg_type = %d .\n", msg->msg_type);
            break;
    }
}

void main(int argc, char *argv[])
{
    message_t msg;
    object_t * cur_obj = NULL;
    object_t * process_obj = NULL;

    cur_obj = (object_t *)malloc(sizeof(object_t));
    cur_obj->object_id = 1;
    cur_obj->def_cb = msg_process;
    cur_obj->handle = (int *)cur_obj;  // 將cur_obj的地址賦給handle

    msg.handle = cur_obj->handle;       //通過msg.handle傳遞cur_obj
    msg.msg_type = atoi(argv[1]);
    
    process_obj = (object_t *)msg.handle;   //通過msg.handle傳遞cur_obj
    process_obj->def_cb(&msg);

    if(cur_obj != NULL)
    {
        free(cur_obj);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章