axsoft
版主
發表:681 回覆:1056 積分:969 註冊:2002-03-13
發送簡訊給我
|
何謂callback? 作者:AOL Server Page 簡單的說,如果你使用了某個function,那麼你就是『call』了一個function。
如果有個系統或是函式是要求你給他一個function,這個function多半都是你自
己寫的。然後他會在適當的時間呼叫你這個function。那麼你的方式就是被呼叫
『callback』了。
舉一個C的例子來說...
#include
#include
#include
#include
#include
#include
#define DEFAULT_BLOCK_SIZE (4096)
typedef void (* CALLBACK) (int);
void ShowPercentage(int percentage)
{
fprintf(stderr, "%d\%\n", percentage);
}
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( (totalReadBytes*100) /fs.st_size);
}
close(fdTrg);
close(fdSrc);
}
int main(void)
{
CopyFile("A.TXT", "B.TXT", ShowPercentage);
return 0 ;
}
時間就是金錢---[ 發問前請先找找舊文章]
|