何謂callback function,在google找到一篇相關(guān)的解釋
簡單的說危队,如果你使用了某個function聪建,那麼你就是『call』了一個function。如果系統(tǒng)或是函式是要求你給一個function pointer交掏,這個function pointer指到一個實際的函式(多半這個函式是你自己寫的)妆偏。然後它會在適當(dāng)?shù)臅r間呼叫此function,則此function就是所謂的 callback function盅弛。因為這個function是被『callback』了钱骂。
舉一個C的例子來說:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define DEFAULT_BLOCK_SIZE (4096)
// 定義callback function的prototype。
typedef void (* CALLBACK) (int);
// 定義了一個名為ShowPercentage的函式挪鹏。這就是我們的callback函式见秽。
// 他的prototype必須與前面的CALLBACK宣告一致。
void ShowPercentage(int percentage)
{
fprintf(stderr, "%dn%nn", percentage);
}
// 定義了一個CopyFile的函式讨盒,這個函式會將參數(shù)source所指定檔案複製到
// target參數(shù)所指定的檔案去解取。而且每複製DEFAULT_BLOCK_SIZE數(shù)量的資料
// 就會呼叫一次callback參數(shù)所指到function一次。
void CopyFile(const char *source, const char *target, CALLBACK callback)
{
char buf[DEFAULT_BLOCK_SIZE] ;
struct stat fs ;
int fdSrc, fdTrg ;
int readBytes = 0, totalReadBytes = 0, percentage = 0;
fdSrc = open(source, O_RDONLY);
fstat(fdSrc, &fs);
fdTrg = open(target,O_CREAT|O_TRUNC|O_RDWR);
// 主要複製資料的迴圈
while((readBytes=read(fdSrc, buf, DEFAULT_BLOCK_SIZE)) > 0)
{
write(fdTrg, buf, readBytes);
totalReadBytes += readBytes ;
//複製資料後就呼叫callback函式去做顯示百分比的動作返顺。
callback( (totalReadBytes*100)/fs.st_size);
}
close(fdTrg);
close(fdSrc);
}
int main(void)
{
// 這個範(fàn)例中只是利用callback來顯示目前的進度禀苦。
// 實際上我們可以利用callback來做更多的動作。
CopyFile("A.TXT", "B.TXT", ShowPercentage);
return 0 ;
}