iT邦幫忙

23

何謂callback function?

  • 分享至 

  • xImage
  •  

何謂callback function,在google找到一篇相關的解釋
簡單的說,如果你使用了某個function,那麼你就是『call』了一個function。如果系統或是函式是要求你給一個function pointer,這個function pointer指到一個實際的函式(多半這個函式是你自己寫的)。然後它會在適當的時間呼叫此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的函式,這個函式會將參數source所指定檔案複製到
// target參數所指定的檔案去。而且每複製DEFAULT_BLOCK_SIZE數量的資料
// 就會呼叫一次callback參數所指到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)
{
    // 這個範例中只是利用callback來顯示目前的進度。
    // 實際上我們可以利用callback來做更多的動作。
    CopyFile("A.TXT", "B.TXT", ShowPercentage);
    return 0 ;
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
jjw
iT邦研究生 1 級 ‧ 2008-07-16 21:45:12

謝謝分享

0
kuochiahao
iT邦研究生 1 級 ‧ 2008-07-17 15:34:37

謝謝分享

0
pqr0007
iT邦研究生 1 級 ‧ 2008-07-24 15:50:14

感謝上面的分享...

0
pqr0007
iT邦研究生 1 級 ‧ 2008-08-05 15:46:44

something like 室內電話 回call 功能??...

我要留言

立即登入留言