ºìÁªLinuxÃÅ»§
Linux°ïÖú

Linux Callback

·¢²¼Ê±¼ä:2008-09-18 21:30:20À´Ô´:ºìÁª×÷Õß:joyrce
×÷Õߣºzxuhong

»Øµ÷º¯ÊýÊdzÌÐòÔ±²»ÄÜÏÔʽµØµ÷Óú¯Êý£¬¶ùʱͨ¹ý½«»Øµ÷º¯ÊýµÄµØÖ·´«¸øµ÷ÓÃÕß´Ó¶øʵÏÖº¯Êýµ÷Óá£ÒªÊµÏֻص÷£¬±ØÐëÊ×Ïȶ¨Ò庯ÊýÖ¸Õë¡£

void fun()£» // º¯ÊýÔ­ÐÍ

¸ÃÓï¾äÉùÃ÷ÁËÒ»¸öº¯Êý£¬Ã»ÓвÎÊý²¢·µ»Øvoid¡£

void (*funPtr) ()£»// º¯ÊýÖ¸Õë

¸ÃÓï¾äÉùÃ÷ÁËÒ»¸öº¯ÊýÖ¸Õ룬×ó±ßÔ²À¨»¡ÖеÄÐǺÅÊǺ¯ÊýÖ¸ÕëÉùÃ÷µÄ¹Ø¼ü£¬ÓÒ±ßÔ²À¨ºÅÊǺ¯ÊýµÄ²ÎÊý£¨ÕâÀï²»´ø²ÎÊý£©£¬º¯ÊýµÄ·µ»ØÀàÐÍvoid£©¡£

typedef void (*FUNC) ()£»// Ϊº¯ÊýÖ¸ÕëÉùÃ÷ÀàÐͶ¨Òå

¸ÃÓï¾äΪº¯ÊýÖ¸ÕëÉùÃ÷ÀàÐͶ¨Ò壬FUNCÊÇÒ»¸öº¯ÊýÖ¸Õ룬ËüÖ¸ÏòµÄº¯ÊýûÓÐÊäÈë²ÎÊý£¬·µ»ØÀàÐÐΪvoid¡£Ê¹ÓÃÕâ¸öÀàÐͶ¨ÒåÃû¿ÉÒÔÒþ²Ø¸´Ôӵĺ¯ÊýÖ¸ÕëÓï·¨¡£

»Øµ÷º¯ÊýµÄʵÏÖ·½Ê½
ÒýÓÃ:
void caller(void (*ptr)() )
{
ptr(); // µ÷ÓÃptrÖ¸ÏòµÄº¯Êý
}
void func()
{
// do something
}
int main()
{
caller(func); // ´«µÝº¯ÊýµØÖ·µ½µ÷ÓÃÕß ptr = func
}


void (*ptr) (); ptrÊÇÊÇÖ¸Ïòijº¯ÊýµÄÖ¸Õ룬¸Ãº¯ÊýÎÞÊäÈë²ÎÊý£¬·µ»ØÀàÐÍÊÇvoid¡£×ó±ßÔ²À¨»¡ÀïÐǺźóµÄ¾ÍÊÇÖ¸Õë±äÁ¿Ãû¡£ÓÐÁËÖ¸Õë±äÁ¿±ã¿ÉÒÔ¸³Öµ£¬ÖµµÄÄÚÈÝÊÇÊðÃûÆ¥ÅäµÄº¯ÊýÃûºÍ·µ»ØÀàÐÍ¡£

void caller(void (*ptr)()); º¯Êýcaller½«µ÷ÓÃptrÖ¸ÏòµÄº¯Êý£¬´Ëº¯ÊýÃûÊÇδ֪µÄ¡£

caller(func); º¯ÊýÖ¸Õëptr = func£¬ptrµÄ¸³Öµ¿ÉÒÔ²»Í¬£¬µ«Ò»¶¨ÒªÊǺ¯ÊýµÄµØÖ·£¬²¢ÇÒÊðÃûºÍ·µ»ØÀàÐÍÏàͬ¡£Èç¹û¸³¸øptr²»Í¬µÄÖµ£¨²»Í¬µÄº¯ÊýµØÖ·£©£¬ÄÇôµ÷ÓÃÕß½«µ÷Óò»Í¬µØÖ·µÄº¯Êý¡£¸³Öµ¿ÉÒÔ·¢ÉúÔÚÔËÐÐʱ£¬ÕâÑù¿ÉÒÔʵÏÖ¶¯Ì¬°ó¶¨¡£

ÏÂÃæ¿´¾ßÌåµÄ»Øµ÷º¯ÊýµÄʵÀý.

ÒýÓÃ:
$ vi callback1.c

#include

int mycb(int a)
{
printf("parameter = %d\n", a);
return(0);
}

int callbackfn(int (*func)(int), int data)
{
func(data);
return(0);
}

int main(void)
{
callbackfn(mycb, 111);

return(0);
}


±àÒë¡¢ÔËÐУº

ÒýÓÃ:
$ gcc callback1.c -o callback1
$ ./callback1
parameter = 111


ÉÏÃæµÄÀý×ÓÒÔÕûÐÍ×÷Ϊº¯ÊýµÄ²ÎÊý£¬ÏÂÃæµÄÀý×ÓÓýṹÌå×÷Ϊº¯ÊýµÄ²ÎÊý¡£

ÒýÓÃ:
$ vi callback2.c

#include
#include

struct person
{
char name[20];
int age;
};

int mycb(struct person p1)
{
printf("name = %s, age = %d\n", p1.name, p1.age);
return(0);
}

int callbackfn(int (*func)(struct person ), struct person person1)
{
func(person1);
return(0);
}

int main(void)
{
struct person one;
strcpy(one.name, "hongdy");
one.age = 30;

callbackfn(mycb, one);

return(0);
}


±àÒë¡¢ÔËÐУº

ÒýÓÃ:
$ gcc callback2.c -o callback2
$ ./callback2
name = hongdy, age = 30


ÏÂÃæµÄÀý×Ó¶¨ÒåÁËtypedef int (*FUNC)(int )£¬ ʹÓÃʱֱ½ÓʹÓÃFUNC ¼´¿É¡£

ÒýÓÃ:
$ vi callback3.c

#include

typedef int (*FUNC)(int );

int mycb(int a)
{
printf("parameter = %d\n", a);
return(0);
}

int callbackfn(FUNC func, int data)
{
func(data);
return(0);
}

int main(void)
{
callbackfn(mycb, 111);

return(0);
}


±àÒë¡¢ÔËÐУº

ÒýÓÃ:
$ gcc callback3.c -o callback3
$ ./callback3
parameter = 111
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 0 ÌõÆÀÂÛ