COM 教程 计算机 英文.docx
IntroductionFormanypeople,learningCOMandDCOMistough.YouknowthatlearningCOMistherightthingtodo-youhearconstanthypeandyouknowthatmanyofMicrosoft,sproductsandprogrammertoolsarebasedonCOM,soitisobviouslysomethingthatisimportant.ButyoualsoknowthatCOMisreallyhard.YoumayhavealreadytriedtolearnCOMonce,ormaybeevenseveraltimes.Youmayhaveslidthroughacoupleofbooks,playedwithsomewizards,etc.Butitjustdoesn,tmakeanysense.Everythingseemsextremelycomplicatedandmuchharderthanitneedstobe.There,salsothevocabulary:"marshalling","apartmentthreads”,z,singletonobjects“andsoon.Whatisthis?ThepurposeofthissetoftutorialsistohelpyoutoquicklyunderstandwhatisgoingonintheworldofDCOMsothatyoucancreateCOMclientsandserverseasily.Wedothatstartingatthebeginningandlayingthingsoutforyousimplyandintherightorder.BythetimeyoufinishthesetutorialsyouwillunderstandallofthebasicconceptsdrivingDCOMandyouwillbeabletoproceedquicklytolearntherest.YouwillbeamazedathoweasyDCOMcanbeonceyougetagoodstart. TheBaSiCSOfCOM-thebestplacetostartisatthebeginning. SimDIeCoMCIientS-COMclientsareeasy SimPIeCOMSerVerS-usingtheAT1.wizardtobuildaserverTheBasicsofCOMUnderstandinghowCOMworkscanbeintimidatingatfirst.OnereasonforthisintimidationisthefactthatCOMusesitsownvocabulary.AsecondreasonisthatCOMcontainsanumberofnewconcepts.OneoftheeasiestwaystomasterthevocabularyandconceptsistocompareCOMobjectstonormalC+objectstoidentifythesimilaritiesanddifferences.YoucanalsomapunfamiliarconceptsfromCOMintothestandardC+modelthatyoualreadyunderstand.Thiswillgiveyouacomfortablestartingpoint,fromwhichwelllookatCOM'sfundamentalconcepts.Oncewehavedonethis,theexamplepresentedinthefollowingsectionswillbeextremelyeasytounderstand.ClassesandObjectsImaginethatyouhavecreatedasimpleclassinC+calledxxx.Ithasseveralmemberfunctions,namedMethodA,MethodB,andMethodC.Eachmemberfunctionacceptsparametersandreturnsaresult.Theclassdeclarationisshownhere:classxxxpublic:intMethodA(inta);intMethodB(floatb);floatMethodC(floatc);;Theclassdeclarationitselfdescribestheclass.Whenyouneedtousetheclass,youmustcreateaninstanceoftheobject.Instantiationsaretheactualobjects;classesarejustthedefinitions.Eachobjectiscreatedeitherasavariable(localorglobal)oritiscreateddynamicallyusingthenewstatement.Thenewstatementdynamicallycreatesthevariableontheheapandreturnsapointertoit.Whenyoucallmemberfunctions,youdosobydereferencingthepointer.Forexample:xxx*px;/px=newxxx;/p->MethodA(l);/deletepx;/pointertoxxxclasscreateobjectonheapcallmethodfreeobjectItisimportantforyoutounderstandandrecognizethatCOMfollowsthissameobjectedorientedmodel.COMhasclasses,memberfunctionsandinstantiationsjustlikeC+objectsdo.AlthoughyounevercallnewonaCOMobject,youmuststillcreateitinmemory.YouaccessCOMobjectswithpointers,andyoumustde-allocatethemwhenyouarefinished.WhenwewriteCOMcode,wewon'tbeusingnewanddelete.Althoughwe,regoingtouseC+asourlanguage,we'llhaveawholenewsyntax.COMisimplementedbycallstotheCOMAPI,whichprovidesfunctionsthatcreateanddestroyCOMobjects.Here'sanexampleCOMprogramwritteninpsedo-COMcode.ixx*pi/CoCreateInstance(,&pi)/pi->MethodA();/pi->Release();/pointertoxxxCOMinterfacecreateinterfacecallmethodfreeinterfaceInthisexample,we'llcallclassixxan"interface".Thevariablepiisapointertotheinterface.ThemethodCoCreateInstancecreatesaninstanceoftypeixx.Thisinterfacepointerisusedtomakemethodcalls.Releasedeletestheinterface.vepurposelyomittedtheparameterstoCoCreateInstance.Ididthissoasnottoobscurethebasicsimplicityoftheprogram.CoCreateInstancetakesanumberofarguments,allofwhichneedsomemoredetailedcoverage.Fornow,let'stakeastepbackandlookatthebiggerissueswithCOM.HowCOMIsDifferentCOMisnotC+,andforgoodreason.COMobjectsaresomewhatmorecomplicatedthentheirC+brethren.Mostofthiscomplicationisnecessarybecauseofnetworkconsiderations.TherearefourbasicfactorsdictatingthedesignofCOM:C+objectsalwaysruninthesameprocessspace.COMobjectscanrunacrossprocessesoracrosscomputers. COMmethodscanbecalledacrossanetwork.C+methodnamesmustbeuniqueinagivenprocessspace.COMobjectnamesmustbeuniquethroughouttheworld. COMserversmaybewritteninavarietyofdifferentlanguagesandonentirelydifferentoperatingsystems,whileC÷+objectsarealwayswritteninC+.1.et'slookatwhatthesedifferencesbetweenCOMandC+meantoyouasaprogrammer.COMcanrunacrossprocessesInCOM,youastheprogrammerareallowedtocreateobjectsinotherprocesses,andonanymachineonthenetwork.ThatdoesnotmeanthatyouW川alwaysdoit(inmanycasesyouwon't).However,thepossibilitymeansthatyoucan'tcreateaCOMobjectusingthenormalC+newstatement,andcallingitsmethodswithlocalprocedurecallswon'tsuffice.TocreateaCOMobject,someexecutingentity(anEXEoraService)willhavetoperformremotememoryallocationandobjectcreation.Thisisaverycomplextask.Byremote,wemeaninanotherprocessoronanotherprocess.ThisproblemissolvedbycreatingaconceptcalledaCOMserver.ThisotherentityW川havetomaintaintightcommunicationwiththeclient.COMmethodscanbecalledacrossanetworkIfyouhaveaccesstoamachineonthenetwork,andifaCOMserverfortheobjectyouwanttousehasbeeninstalledonthatmachine,thenyoucancreatetheCOMobjectonthatcomputer.Ofcourse,youmusttheproperprivileges,andeverythinghastobeset-upcorrectlyontheothercomputer.SinceyourCOMobjectwillnotnecessarilybeonthelocalmachine,youneedagoodwayto"pointto"it,eventhoughitsmemoryissomewhereelse.Technically,thereisnowaytodothis.Inpractice,itcanbesimulatedbyintroducingawholenewlevelofobjects.OneofthewaysCOMdoesthisiswithaconceptcalledaproxystb.Welldiscussproxy/stubsinsomedetaillater.AnotherimportantissueispassingdatabetweentheCOMclientandit'sCOMserver.Whendataispassedbetweenprocesses,threads,oroveranetwork,itiscalled"Marshalling".Again,theproxystbtakescareofthemarshallingforyou.COMcanalsomarshaldataforcertaintypesofinterfaceusingType1.ibrariesandtheAutomationmarshaller.TheAutomationmarshallerdoesnotneedtobespecificallybuiltforeachCOMserver.COMobjectsmustbeuniquethroughouttheworldThewholeworld?Comeon!Thismayseemlikeanexaggerationatfirst,butconsidertheInternettobeaworldwidenetwork.Evenifyou'reworkingonasinglecomputer,COMmusthandlethepossibility.Uniquenessistheissue.InC+allclassesarehandledunequivocallybythecompiler.Thecompilercanseetheclassdefinitionforeveryclassusedinaprogramandmatchupallreferencestoittomakesuretheyconformtotheclassexactly.Thecompilercanalsoguaranteethatthereisonlyoneclassofagivenname.InCOMtheremustbeagoodwaytogetasimilarlyunequivocalmatch.COMmustguaranteethatthereW川OnIybeoneobjectofagivennameeventhoughthenumberofobjectsavailableonaworldwidenetworkishuge.ThisproblemissolvedbycreatingaconceptcalledaGUID.COMislanguageindpendentCOMserversmaybewrittenwithadifferentlanguageandanentirelydifferentoperatingsystem.COMobjectshavethecapabilityofbeingremotelyaccessible.Thatmeanstheymaybeinadifferentthread,process,orevenonadifferentcomputer.Theothercomputermayevenberunningunderadifferentoperatingsystem.Thereneedstobeagoodwaytotransmitparametersoverthenetworktoobjectsonothermachines.Thisproblemissolvedbycreatinganewwaytocarefullyspecifytheinterfacebetweentheclientandserver.ThereisalsoanewcompilercalledMID1.(Microsoft?lnterfaceDefinition1.anguage).Thiscompilermakesitpossibletogenericallyspecifytheinterfacebetweentheserverandclient.MID1.definesCOMobjects,interfaces,methodsandparameters.COMVocabularyOneoftheproblemswe,regoingtohaveiskeepingtrackoftwosetsofterminology.You'reprobablyalreadyfamiliarwithC+andsomeObjectOrientedterminology.ThistableprovidesaroughequivalencybetweenCOMandconventionalterminology.ConceptConventional(C+OOP)COMClientAprogramthatrequestservicesfromaserver.AprogramthatcallsCOMmethods.ServerAprogramthat"serves"otherprograms.AprogramthatmakesCOMobjectsavailabletoaCOMclient.InterfaceNone.ApointertoagroupoffunctionsthatarecalledthroughCOM.ClassAdatatype.Definesagroupofmethodsanddatathatareusedtogether.ThedefinitionofanobjectthatimplementsoneormoreCOMinterfaces.Also,"coclass".ObjectAninstanceofaclass.Theinstanceofacoclass.MarshallingNone.Movingdatabetweenclientandserver.You'llnoticetheconceptsofInterfaceandMarshallingdon'ttranslatewellintotheC+model.TheclosestthingtoaninterfaceinC+istheexportdefinitionsofaD1.1.D1.1.'sdomanyofthesamethingsasCOMwhendealingwithatightlycoupled(in-process)COMserver.MarshallinginC+isalmostentirelymanual.Ifyou'retryingtocopydatabetweenprocessesandcomputers,you'llhavetowritethecodeusingsomesortofinter-processcommunication.Youhaveseveralchoices,includingsockets,theclipboard,andmailslots.TheInterfaceThusfar,we,vebeenusingtheword"interface"prettyloosely.Mydictionary(1947AmericanCollegeDictionary)definesaninterfaceasfollows:"Interface,n.asurfaceregardedasthecommonboundaryoftwobodiesorsurfaces"That'sactuallyausefulgeneraldescription.InCOM"interface"hasaveryspecificmeaning.COMinterfacesareacompletelynewconcept,notavailableinC+.Theconceptofaninterfaceisinitiallyhardtounderstandformanypeople.Aninterfaceisaghostlikeentitythatneverhasaconcreteexistence.It'ssortoflikeanabstractclass-butnotexactly.Atitssimplest,aninterfaceisnothingbutanamedcollectionoffunctions.InC+,aclass(usingthisterminology)isallowedonlyoneinterface.Thememberfunctionsofthatinterfaceareallthepublicmemberfunctionsoftheclass.Inotherwords,theinterfaceisthepubliclyvisiblepartoftheclass.InC+thereisalmostnodistinctionbetweenaninterfaceandaclass.Here'sanexampleC+class:classyyypublic:intDoThisO;private:voidHelperl();intcount;intx,y,z;);Whensomeonetriestousethisclass,theyonlyhaveaccesstothepublicmembers.(Forthemomentwe,reignoringprotectedmembersandinheritance.)Theycan'tcallHelperl,oruseanyoftheprivatevariables.Totheconsumerofthisclass,thedefinitionlookslikethis:classyyyintDoThisO;;Thispublicsubsetoftheclassisthe'interface'totheoutsideworld.Essentiallytheinterfacehidesthegutsoftheclassfromtheconsumer.ThisC+analogyonlygoessofar.ACOMinterfaceisnotaC+class.COMinterfacesandclasseshavetheirownspecialsetofrulesandconventions.COMallowsacoclass(COMclass)tohavemultipleinterfaces,eachinterfacehavingitsownnameanditsowncollectionoffunctions.Thereasonforthisfeatureistoallowformorecomplexandfunctionalobjects.ThisisanotherconceptthatisalientoC+.(Perhapsmultipleinterfacescouldbeenvisionedasaunionoftwoclassdefinitions-somethingthatisn'tallowedinC÷+.)InterfacesisolatetheclientfromtheserverOneofthecardinalrulesofCOMisthatyoucanonlyaccessaCOMobjectthroughaninterface.Theclientprogramiscompletelyisolatedfromtheserver'simplementationthroughinterfaces.Thisisanextremelyimportantpoint.TheclientprogramknowsnothingabouttheCOMobjectorC+classthatimplementstheCOMobject.Allitcanseeistheinterface.TheinterfaceislikewindowintotheCOMobject.Theinterfacedesignerallowstheclienttoseeonlythosepartsoftheobjectthatheorshewishestoexpose.Figure2-1illustrateshowallclientaccesstotheCOMobjectisfeledthroughtheinterface.FigUreThenotationusedhere,asmallcircleconnectedbyastick,istheconventionalwaytodrawaCOMinterface.Therearemanyimportantrulesassociatedwithinterfaces.WhilecriticalforunderstandingthedetailshowCOMworks,wecanleavethemuntillater.Fornow,wellconcentrateonthebroadconceptsofinterfaces.ImaginingaCOMInterfaceHere'sanotherwaytovisualizeaninterface.Inthissectionwe,llpresentaCOMinterfacewithoutanyoftheC+baggage.Welltrytolookataninterfaceinitsabstractform.Imaginea"car"object.All"car"objectsthatyouarefamiliarwithintherealworldhavea"driving"interfacethatallowsyoutodirectthecarleftandrightandalsotospeedthecarupandslowitdown.Thememberfunctionsforthedrivinginterfacemightbe"left","right","faster","slower","forward"and"reverse".Manycarsalsohappentohavea"radio"interfaceaswell,iftheyhavearadioinstalled.Thefunctionsfortheradiointerfacemightbe"on","off","louder","softer","nextstation"and"previousstation".DrivingRadio1.eft()On()Right()otf()Slower()1.ouder()Faster()Softer()ForwardQNextStationOReverse()PrevStationOTherearemanykindsofcars,butnotallofthemhaveradios.Therefore,theydonotimplementtheradiointerface,althoughtheydosupportthedrivinginterface.Inallcarsthatdohaveradiosthecapabilitiesoftheradioarethesame.Apersondrivingacarwithoutaradiocanstilldrive,butcannothearmusic.Inacarthatdoeshavearadio,theradiointerfaceisavailable.COMsupportsthissamesortofmodelforCOMclasses.ACOMobjectcansupportacollectionofinterfaces,eachofwhichhasaname.ForCOMobjectsthatyoucreateyourself,youwilloftendefineandusejustasingleCOMinterface.ButmanyexistingCOMobjectssupportmultipleCOMinterfacesdependingonthefeaturestheysupport.Anotherimportantdistinctionisthatthedrivinginterfaceisnotthecar.Thedrivinginterfacedoesn'ttellyouanythingaboutthebrakes,orthewheels,ortheengineofthecar.Youdon'tdrivetheengineforexample,youusethefasterandslowermethods(acceleratorandbrakes)ofthedrivinginterface.Youdon'treallycarehowtheslower(brake)methodisimplemented,aslongasthecarslowsdown.Whetherthecarhashydraulicorairbrakesisn'timportant.ImagineacomponentWhenyou'rebuildingaCOMobject,youareveryconcernedabouthowtheinterfaceworks.Theuseroftheinterfacehowever,shouldn'tbeconcernedaboutitsimplementation.1.ikethebrakesonacar,theusercaresonlythattheinterfaceworks,notaboutthedetailsbehindtheinterface.ThisisolationofinterfaceandimplementationiscrucialforCOM.Byisolatingtheinterfacefromit'simplementation,wecanbuildcomponents.Componentscanbereplacedandre-used.Thisbothsimplifiesandmultipliestheusefulnessoftheobject.What'sinaname?OneimportantfacttorecognizeisthatanamedCOMinterfaceisunique.Thatis,aprogrammerisallowedtomakeanassumptioninCOMthatifheaccessesaninterfaceofaspecificname,thememberfunctionsandparametersofthatinterfaceW川beexactlythesameinallCOMobjectsthatimplementtheinterface.So,followingourexample,theinterfacesnamed"driving"and"radio"willhaveexactlythesamememberfunctionsignatureinanyCOMobjectthatimplementsthem.Ifyouwanttochangethememberfunctionsofaninterfaceinanywaytyouhavetocreateanewinterfacewithanewname.Thesourceofallinterfaces-IUnknownTraditionalexplanationsofCOMstartoutwithathoroughdescriptionofthe(Unknowninterface.!UnknownisthefundamentalbasisforallCOMinterfaces.Despiteitsimportance,youdon'tneedtoknowabout!Unknowntounderstandtheinterfaceconcept.Theimplementationof!Unknownishiddenbythehigherlevelabstractionswe'llbeusingtobuildourCOMobjects.Actually,payingtoomuchattentionto!Unknowncanbeconfusing.1.et'sdealwithitatahighlevelheresoyouunderstandtheconcepts.(UnknownislikeanabstractbaseclassinC+.AllCOMinterfacesmustinheritfromIUnknown.!Unknownhandlesthecreationandmanagementoftheinterface.Themethodsof!Unknownareusedtocreate,referencecount,andreleaseaCOMobject.AllCOMinterfacesimplementthese3methodsandtheyareusedinternallybyCOMtomanageinterfaces.Youwilllikelynevercallthese3methodsyourself.AtypicalCOMobjectNowlet'sputallofthesenewconceptstogetheranddescribeatypicalCOMobjectandaprogramthatwantstoaccessit.Inthenextsectionandthefollowingchapterswewillmakethisrealbyimplementingtheactualcodefortheobject.ImaginethatyouwanttocreatethesimplestpossibleCOMobject.Thisobjectwillsupportasingleinterface,andthatinterfacewillcontainasin