A "callback" is any function that is called by another function which takes the first function as a parameter. That is, when function F1 calls ...
Clanguagecallbackfunctiondetailsandexamples
Keywords:
C
1.Whatisacallbackfunction?Callbackfunction,justlistentothenameishigherthanordinaryfunctions.Whatisacallbackfunction?I'msorryIhaven'treadmuch.Ihaven'tseenthedefinitionofcallbackfunctioninanybook.IsearchedBaiduandfoundthattherearedifferentopinions.Alargepartofthemuseasimilarscenetoexplain:whenaJungoestoBJun'sstoretobuysomething,ithappenstobeoutofstock.AJunleavesanumbertoBJunandnotifiesaJunwhenitisavailable.Itseemsthatasynchronousoperationiseasiertothinkofthancallback.Inaddition,therearetwoEnglishsentencesthatimpressme:1)Ifyoucallme,Iwillcallyouback;2)Don'tcallme,Iwillcallyou?Therefore,Idon'tthinksuchstatementsareveryappropriate,becauseIdon'tthinkthesestatementsexpressthecharacteristicsofcallbackfunctions,thatis,theycan'tseethedifferencebetweencallbackfunctionsandordinaryfunctions.However,Ithinkit'sprettygoodtomakecomplaintsaboutBaiduEncyclopedia(thoughIoftensearchBaidusearch):callbackfunctionisafunctioncalledbyfunctionpointer.Ifyoupassthepointer(address)ofafunctionasaparametertoanotherfunction,whenthepointerisusedtocallthefunctionitpointsto,wesayitisacallbackfunction.
Let'stalkaboutmyopinionfirst.Wecanliterallydecomposeitfirst.For"callbackfunction",Chinesecanactuallyunderstandtwomeanings:1)thecallbackfunction;2)Gobacktothefunctionthatcalledtheaction.Whatthehellisthiscallback?
Incomputerprogramming,acallbackisanyexecutablecodethatispassedasanargumenttoothercode,whichisexpectedtocallback(execute)theargumentatagiventime.Thisexecutionmaybeimmediateasinasynchronouscallback,oritmighthappenatalatertimeasinanasynchronouscallback.Ifthecodeisexecutedimmediately,itiscalledasynchronousCallback.Ifitisexecutedlater,itiscalledanasynchronousCallback.Synchronousandasynchronousarenotdiscussedhere.Pleaserefertorelevantmaterials.
A"callback"isanyfunctionthatiscalledbyanotherfunctionwhichtakesthefirstfunctionasaparameter.Thatis,whenfunctionF1callsfunctionF2,functionF1passesthepointerofanotherfunctionF3tofunctionF2throughparameters.DuringtheexecutionoffunctionF2,functionF2callsfunctionF3.Thisactioniscalledcallback,andthefunctionF3firstpassedasapointerandthencalledbackisthecallbackfunction.Nowyoushouldunderstandthedefinitionofcallbackfunction?
2.Whyusecallbackfunction?Manyfriendsmaythink,whynotwritethenameofthefunctiondirectlyinthecallbackplacelikeordinaryfunctioncalls?Isn'tthatok?WhydoIhavetousecallbackfunctions?It'sagoodideabecausemanyexamplesofparsingcallbackfunctionscanbecalledwithordinaryfunctions.Toanswerthisquestion,let'sfirstunderstandthebenefitsandfunctionsofreturningtofunctions,thatis,decoupling.Yes,it'ssuchasimpleanswer.Becauseofthisfeature,ordinaryfunctionscan'treplacecallbackfunctions.Therefore,inmyeyes,thisisthebiggestfeatureofcallbackfunctions.Let'stakealookatapictureonWikipediathatIthinkiswelldrawn.ThefollowingisanincompleteClanguagecodetoshowthemeaningoftheabovefigure:
example
#include
#Include//containstheheaderfileofthereadSoftwarelibrarywheretheLibraryFunctionislocated
intCallback()//CallbackFunction
{
//TODO
return0;
}
intmain()//Mainprogram
{
//TODO
Library(Callback);
//TODO
return0;
}
Atfirstglance,thecallbackseemstobejustacallbetweenfunctions,whichisnodifferentfromordinaryfunctioncalls,butacloserlookshowsakeydifferencebetweenthetwo:inthecallback,themainprogrampassesthecallbackfunctionintothefunctionlikeaparameter.Inthisway,aslongaswechangetheparameterspassedintothelibraryfunction,wecanrealizedifferentfunctions.Doyouthinkitisveryflexible?Andthereisnoneedtomodifytheimplementationoflibraryfunctions,whichisdecoupling.Takeacloserlook.Themainfunctionandcallbackfunctionareonthesamelayer,whilethelibraryfunctionisonanotherlayer.Thinkaboutit.Ifthelibraryfunctionisinvisibletous,wecan'tmodifytheimplementationofthelibraryfunction,thatis,wecan'tmodifythelibraryfunctiontocallordinaryfunctions,sowecanonlypassindifferentcallbackfunctions,Thisisacommonsituationindailywork.Nowputthemain(),Library(),andCallback()functionsbackintotheF1,F2,andF3functions.Isthatmoreclear?
Afterunderstandingthecharacteristicsofcallbackfunction,canyouroughlyknowunderwhatcircumstancesitshouldbeused?Yes,youcanusecallbackfunctionsinmanyplacesinsteadofordinaryfunctioncalls,butinmyopinion,callbackfunctionsshouldbeusedifyouneedtoreducethecoupling.-----------------------------------------------------------------Instance-----------------------------------------------------------------3.Howtousecallbackfunction?Ifyouknowwhatacallbackfunctionisandthecharacteristicsofacallbackfunction,howshouldyouuseacallbackfunction?Let'stakealookatasimpleexecutablesynchronouscallbackfunctioncode.
example
#include
intCallback_1()//CallbackFunction1
{
printf("Hello,thisisCallback_1");
return0;
}
intCallback_2()//CallbackFunction2
{
printf("Hello,thisisCallback_2");
return0;
}
intCallback_3()//CallbackFunction3
{
printf("Hello,thisisCallback_3");
return0;
}
intHandle(int(*Callback)())
{
printf("EnteringHandleFunction.");
Callback();
printf("LeavingHandleFunction.");
}
intmain()
{
printf("EnteringMainFunction.");
Handle(Callback_1);
Handle(Callback_2);
Handle(Callback_3);
printf("LeavingMainFunction.");
return0;
}
Operationresults:
EnteringMainFunction.
EnteringHandleFunction.
Hello,thisisCallback_1
LeavingHandleFunction.
EnteringHandleFunction.
Hello,thisisCallback_2
LeavingHandleFunction.
EnteringHandleFunction.
Hello,thisisCallback_3
LeavingHandleFunction.
LeavingMainFunction.
YoucanseethattheparameterintheHandle()functionisApointer.WhencallingtheHandle()functioninthemain()function,thefunctioncallbackispassedintoit_1()/Callback_2()/Callback_3(),thefunctionnameatthistimeisthepointerofthecorrespondingfunction,thatis,thecallbackfunctionisactuallyAuseoffunctionpointer.Nowreadthissentenceagain:A"callback"isanyfunctionthatiscalledbyanotherfunctionwhichtakesthefirstfunctionasaparameter?
4.Howtousecallbackfunctionwithparameters?Sharpeyedfriendsmayfindthatthecallbackfunctioninthepreviousexamplehasnoparameters,socanwecallbackthosefunctionswithparameters?Theanswerisyes.Sohowtocallit?Wecanmodifytheaboveexampleslightly:
example
#include
intCallback_1(intx)//CallbackFunction1
{
printf("Hello,thisisCallback_1:x=%d",x);
return0;
}
intCallback_2(intx)//CallbackFunction2
{
printf("Hello,thisisCallback_2:x=%d",x);
return0;
}
intCallback_3(intx)//CallbackFunction3
{
printf("Hello,thisisCallback_3:x=%d",x);
return0;
}
intHandle(inty,int(*Callback)(int))
{
printf("EnteringHandleFunction.");
Callback(y);
printf("LeavingHandleFunction.");
}
intmain()
{
inta=2;
intb=4;
intc=6;
printf("EnteringMainFunction.");
Handle(a,Callback_1);
Handle(b,Callback_2);
Handle(c,Callback_3);
printf("LeavingMainFunction.");
return0;
}
Operationresults:
EnteringMainFunction.
EnteringHandleFunction.
Hello,thisisCallback_1:x=2
LeavingHandleFunction.
EnteringHandleFunction.
Hello,thisisCallback_2:x=4
LeavingHandleFunction.
EnteringHandleFunction.
Hello,thisisCallback_3:x=6
LeavingHandleFunction.
LeavingMainFunction.
Asyoucansee,insteadofdirectlychangingintHandle(int(*Callback)(int))tointHandle(int(*Callback)(int)),youcanaddanotherparametertosavetheparametervalueofthecallbackfunction,suchastheparameterYofintHandle(inty,int(*Callback)(int)).Similarly,callbackfunctionswithmultipleparameterscanbeused.
PostedbywerkkrewonMon,06Dec202112:51:50-0800
HotKeywords
Java-6961
Database-2683
Python-2616
Programming-2419
Attribute-2418
Javascript-2383
Spring-2111
Android-2077
xml-1972
Linux-1818
JSON-1764
network-1748
github-1720
less-1676
MySQL-1538
SQL-1332
PHP-1318
encoding-1179
Mobile-1029
Apache-925