COM 教程 计算机 英文.docx

上传人:夺命阿水 文档编号:1407251 上传时间:2024-06-15 格式:DOCX 页数:52 大小:129.68KB
返回 下载 相关 举报
COM 教程 计算机 英文.docx_第1页
第1页 / 共52页
COM 教程 计算机 英文.docx_第2页
第2页 / 共52页
COM 教程 计算机 英文.docx_第3页
第3页 / 共52页
COM 教程 计算机 英文.docx_第4页
第4页 / 共52页
COM 教程 计算机 英文.docx_第5页
第5页 / 共52页
点击查看更多>>
资源描述

《COM 教程 计算机 英文.docx》由会员分享,可在线阅读,更多相关《COM 教程 计算机 英文.docx(52页珍藏版)》请在课桌文档上搜索。

1、IntroductionFormanypeople,learningCOMandDCOMistough.YouknowthatlearningCOMistherightthingtodo-youhearconstanthypeandyouknowthatmanyofMicrosoft,sproductsandprogrammertoolsarebasedonCOM,soitisobviouslysomethingthatisimportant.ButyoualsoknowthatCOMisreallyhard.YoumayhavealreadytriedtolearnCOMonce,ormay

2、beevenseveraltimes.Youmayhaveslidthroughacoupleofbooks,playedwithsomewizards,etc.Butitjustdoesn,tmakeanysense.Everythingseemsextremelycomplicatedandmuchharderthanitneedstobe.There,salsothevocabulary:marshalling,apartmentthreads”,z,singletonobjects“andsoon.Whatisthis?Thepurposeofthissetoftutorialsist

3、ohelpyoutoquicklyunderstandwhatisgoingonintheworldofDCOMsothatyoucancreateCOMclientsandserverseasily.Wedothatstartingatthebeginningandlayingthingsoutforyousimplyandintherightorder.BythetimeyoufinishthesetutorialsyouwillunderstandallofthebasicconceptsdrivingDCOMandyouwillbeabletoproceedquicklytolearn

4、therest.YouwillbeamazedathoweasyDCOMcanbeonceyougetagoodstart. TheBaSiCSOfCOM-thebestplacetostartisatthebeginning. SimDIeCoMCIientS-COMclientsareeasy SimPIeCOMSerVerS-usingtheAT1.wizardtobuildaserverTheBasicsofCOMUnderstandinghowCOMworkscanbeintimidatingatfirst.Onereasonforthisintimidationisthefactt

5、hatCOMusesitsownvocabulary.AsecondreasonisthatCOMcontainsanumberofnewconcepts.OneoftheeasiestwaystomasterthevocabularyandconceptsistocompareCOMobjectstonormalC+objectstoidentifythesimilaritiesanddifferences.YoucanalsomapunfamiliarconceptsfromCOMintothestandardC+modelthatyoualreadyunderstand.Thiswill

6、giveyouacomfortablestartingpoint,fromwhichwelllookatCOMsfundamentalconcepts.Oncewehavedonethis,theexamplepresentedinthefollowingsectionswillbeextremelyeasytounderstand.ClassesandObjectsImaginethatyouhavecreatedasimpleclassinC+calledxxx.Ithasseveralmemberfunctions,namedMethodA,MethodB,andMethodC.Each

7、memberfunctionacceptsparametersandreturnsaresult.Theclassdeclarationisshownhere:classxxxpublic:intMethodA(inta);intMethodB(floatb);floatMethodC(floatc);;Theclassdeclarationitselfdescribestheclass.Whenyouneedtousetheclass,youmustcreateaninstanceoftheobject.Instantiationsaretheactualobjects;classesare

8、justthedefinitions.Eachobjectiscreatedeitherasavariable(localorglobal)oritiscreateddynamicallyusingthenewstatement.Thenewstatementdynamicallycreatesthevariableontheheapandreturnsapointertoit.Whenyoucallmemberfunctions,youdosobydereferencingthepointer.Forexample:xxx*px;/px=newxxx;/p-MethodA(l);/delet

9、epx;/pointertoxxxclasscreateobjectonheapcallmethodfreeobjectItisimportantforyoutounderstandandrecognizethatCOMfollowsthissameobjectedorientedmodel.COMhasclasses,memberfunctionsandinstantiationsjustlikeC+objectsdo.AlthoughyounevercallnewonaCOMobject,youmuststillcreateitinmemory.YouaccessCOMobjectswit

10、hpointers,andyoumustde-allocatethemwhenyouarefinished.WhenwewriteCOMcode,wewontbeusingnewanddelete.Althoughwe,regoingtouseC+asourlanguage,wellhaveawholenewsyntax.COMisimplementedbycallstotheCOMAPI,whichprovidesfunctionsthatcreateanddestroyCOMobjects.HeresanexampleCOMprogramwritteninpsedo-COMcode.ixx

11、*pi/CoCreateInstance(,&pi)/pi-MethodA();/pi-Release();/pointertoxxxCOMinterfacecreateinterfacecallmethodfreeinterfaceInthisexample,wellcallclassixxaninterface.Thevariablepiisapointertotheinterface.ThemethodCoCreateInstancecreatesaninstanceoftypeixx.Thisinterfacepointerisusedtomakemethodcalls.Release

12、deletestheinterface.vepurposelyomittedtheparameterstoCoCreateInstance.Ididthissoasnottoobscurethebasicsimplicityoftheprogram.CoCreateInstancetakesanumberofarguments,allofwhichneedsomemoredetailedcoverage.Fornow,letstakeastepbackandlookatthebiggerissueswithCOM.HowCOMIsDifferentCOMisnotC+,andforgoodre

13、ason.COMobjectsaresomewhatmorecomplicatedthentheirC+brethren.Mostofthiscomplicationisnecessarybecauseofnetworkconsiderations.TherearefourbasicfactorsdictatingthedesignofCOM:C+objectsalwaysruninthesameprocessspace.COMobjectscanrunacrossprocessesoracrosscomputers. COMmethodscanbecalledacrossanetwork.C

14、+methodnamesmustbeuniqueinagivenprocessspace.COMobjectnamesmustbeuniquethroughouttheworld. COMserversmaybewritteninavarietyofdifferentlanguagesandonentirelydifferentoperatingsystems,whileC+objectsarealwayswritteninC+.1.etslookatwhatthesedifferencesbetweenCOMandC+meantoyouasaprogrammer.COMcanrunacros

15、sprocessesInCOM,youastheprogrammerareallowedtocreateobjectsinotherprocesses,andonanymachineonthenetwork.ThatdoesnotmeanthatyouW川alwaysdoit(inmanycasesyouwont).However,thepossibilitymeansthatyoucantcreateaCOMobjectusingthenormalC+newstatement,andcallingitsmethodswithlocalprocedurecallswontsuffice.Toc

16、reateaCOMobject,someexecutingentity(anEXEoraService)willhavetoperformremotememoryallocationandobjectcreation.Thisisaverycomplextask.Byremote,wemeaninanotherprocessoronanotherprocess.ThisproblemissolvedbycreatingaconceptcalledaCOMserver.ThisotherentityW川havetomaintaintightcommunicationwiththeclient.C

17、OMmethodscanbecalledacrossanetworkIfyouhaveaccesstoamachineonthenetwork,andifaCOMserverfortheobjectyouwanttousehasbeeninstalledonthatmachine,thenyoucancreatetheCOMobjectonthatcomputer.Ofcourse,youmusttheproperprivileges,andeverythinghastobeset-upcorrectlyontheothercomputer.SinceyourCOMobjectwillnotn

18、ecessarilybeonthelocalmachine,youneedagoodwaytopointtoit,eventhoughitsmemoryissomewhereelse.Technically,thereisnowaytodothis.Inpractice,itcanbesimulatedbyintroducingawholenewlevelofobjects.OneofthewaysCOMdoesthisiswithaconceptcalledaproxystb.Welldiscussproxy/stubsinsomedetaillater.Anotherimportantis

19、sueispassingdatabetweentheCOMclientanditsCOMserver.Whendataispassedbetweenprocesses,threads,oroveranetwork,itiscalledMarshalling.Again,theproxystbtakescareofthemarshallingforyou.COMcanalsomarshaldataforcertaintypesofinterfaceusingType1.ibrariesandtheAutomationmarshaller.TheAutomationmarshallerdoesno

20、tneedtobespecificallybuiltforeachCOMserver.COMobjectsmustbeuniquethroughouttheworldThewholeworld?Comeon!Thismayseemlikeanexaggerationatfirst,butconsidertheInternettobeaworldwidenetwork.Evenifyoureworkingonasinglecomputer,COMmusthandlethepossibility.Uniquenessistheissue.InC+allclassesarehandledunequi

21、vocallybythecompiler.Thecompilercanseetheclassdefinitionforeveryclassusedinaprogramandmatchupallreferencestoittomakesuretheyconformtotheclassexactly.Thecompilercanalsoguaranteethatthereisonlyoneclassofagivenname.InCOMtheremustbeagoodwaytogetasimilarlyunequivocalmatch.COMmustguaranteethatthereW川OnIyb

22、eoneobjectofagivennameeventhoughthenumberofobjectsavailableonaworldwidenetworkishuge.ThisproblemissolvedbycreatingaconceptcalledaGUID.COMislanguageindpendentCOMserversmaybewrittenwithadifferentlanguageandanentirelydifferentoperatingsystem.COMobjectshavethecapabilityofbeingremotelyaccessible.Thatmean

23、stheymaybeinadifferentthread,process,orevenonadifferentcomputer.Theothercomputermayevenberunningunderadifferentoperatingsystem.Thereneedstobeagoodwaytotransmitparametersoverthenetworktoobjectsonothermachines.Thisproblemissolvedbycreatinganewwaytocarefullyspecifytheinterfacebetweentheclientandserver.

24、ThereisalsoanewcompilercalledMID1.(Microsoft?lnterfaceDefinition1.anguage).Thiscompilermakesitpossibletogenericallyspecifytheinterfacebetweentheserverandclient.MID1.definesCOMobjects,interfaces,methodsandparameters.COMVocabularyOneoftheproblemswe,regoingtohaveiskeepingtrackoftwosetsofterminology.You

25、reprobablyalreadyfamiliarwithC+andsomeObjectOrientedterminology.ThistableprovidesaroughequivalencybetweenCOMandconventionalterminology.ConceptConventional(C+OOP)COMClientAprogramthatrequestservicesfromaserver.AprogramthatcallsCOMmethods.ServerAprogramthatservesotherprograms.AprogramthatmakesCOMobjec

26、tsavailabletoaCOMclient.InterfaceNone.ApointertoagroupoffunctionsthatarecalledthroughCOM.ClassAdatatype.Definesagroupofmethodsanddatathatareusedtogether.ThedefinitionofanobjectthatimplementsoneormoreCOMinterfaces.Also,coclass.ObjectAninstanceofaclass.Theinstanceofacoclass.MarshallingNone.Movingdatab

27、etweenclientandserver.YoullnoticetheconceptsofInterfaceandMarshallingdonttranslatewellintotheC+model.TheclosestthingtoaninterfaceinC+istheexportdefinitionsofaD1.1.D1.1.sdomanyofthesamethingsasCOMwhendealingwithatightlycoupled(in-process)COMserver.MarshallinginC+isalmostentirelymanual.Ifyouretryingto

28、copydatabetweenprocessesandcomputers,youllhavetowritethecodeusingsomesortofinter-processcommunication.Youhaveseveralchoices,includingsockets,theclipboard,andmailslots.TheInterfaceThusfar,we,vebeenusingthewordinterfaceprettyloosely.Mydictionary(1947AmericanCollegeDictionary)definesaninterfaceasfollow

29、s:Interface,n.asurfaceregardedasthecommonboundaryoftwobodiesorsurfacesThatsactuallyausefulgeneraldescription.InCOMinterfacehasaveryspecificmeaning.COMinterfacesareacompletelynewconcept,notavailableinC+.Theconceptofaninterfaceisinitiallyhardtounderstandformanypeople.Aninterfaceisaghostlikeentitythatn

30、everhasaconcreteexistence.Itssortoflikeanabstractclass-butnotexactly.Atitssimplest,aninterfaceisnothingbutanamedcollectionoffunctions.InC+,aclass(usingthisterminology)isallowedonlyoneinterface.Thememberfunctionsofthatinterfaceareallthepublicmemberfunctionsoftheclass.Inotherwords,theinterfaceisthepub

31、liclyvisiblepartoftheclass.InC+thereisalmostnodistinctionbetweenaninterfaceandaclass.HeresanexampleC+class:classyyypublic:intDoThisO;private:voidHelperl();intcount;intx,y,z;);Whensomeonetriestousethisclass,theyonlyhaveaccesstothepublicmembers.(Forthemomentwe,reignoringprotectedmembersandinheritance.

32、)TheycantcallHelperl,oruseanyoftheprivatevariables.Totheconsumerofthisclass,thedefinitionlookslikethis:classyyyintDoThisO;;Thispublicsubsetoftheclassistheinterfacetotheoutsideworld.Essentiallytheinterfacehidesthegutsoftheclassfromtheconsumer.ThisC+analogyonlygoessofar.ACOMinterfaceisnotaC+class.COMi

33、nterfacesandclasseshavetheirownspecialsetofrulesandconventions.COMallowsacoclass(COMclass)tohavemultipleinterfaces,eachinterfacehavingitsownnameanditsowncollectionoffunctions.Thereasonforthisfeatureistoallowformorecomplexandfunctionalobjects.ThisisanotherconceptthatisalientoC+.(Perhapsmultipleinterf

34、acescouldbeenvisionedasaunionoftwoclassdefinitions-somethingthatisntallowedinC+.)InterfacesisolatetheclientfromtheserverOneofthecardinalrulesofCOMisthatyoucanonlyaccessaCOMobjectthroughaninterface.Theclientprogramiscompletelyisolatedfromtheserversimplementationthroughinterfaces.Thisisanextremelyimpo

35、rtantpoint.TheclientprogramknowsnothingabouttheCOMobjectorC+classthatimplementstheCOMobject.Allitcanseeistheinterface.TheinterfaceislikewindowintotheCOMobject.Theinterfacedesignerallowstheclienttoseeonlythosepartsoftheobjectthatheorshewishestoexpose.Figure2-1illustrateshowallclientaccesstotheCOMobje

36、ctisfeledthroughtheinterface.FigUreThenotationusedhere,asmallcircleconnectedbyastick,istheconventionalwaytodrawaCOMinterface.Therearemanyimportantrulesassociatedwithinterfaces.WhilecriticalforunderstandingthedetailshowCOMworks,wecanleavethemuntillater.Fornow,wellconcentrateonthebroadconceptsofinterf

37、aces.ImaginingaCOMInterfaceHeresanotherwaytovisualizeaninterface.Inthissectionwe,llpresentaCOMinterfacewithoutanyoftheC+baggage.Welltrytolookataninterfaceinitsabstractform.Imagineacarobject.Allcarobjectsthatyouarefamiliarwithintherealworldhaveadrivinginterfacethatallowsyoutodirectthecarleftandrighta

38、ndalsotospeedthecarupandslowitdown.Thememberfunctionsforthedrivinginterfacemightbeleft,right,faster,slower,forwardandreverse.Manycarsalsohappentohavearadiointerfaceaswell,iftheyhavearadioinstalled.Thefunctionsfortheradiointerfacemightbeon,off,louder,softer,nextstationandpreviousstation.DrivingRadio1

39、.eft()On()Right()otf()Slower()1.ouder()Faster()Softer()ForwardQNextStationOReverse()PrevStationOTherearemanykindsofcars,butnotallofthemhaveradios.Therefore,theydonotimplementtheradiointerface,althoughtheydosupportthedrivinginterface.Inallcarsthatdohaveradiosthecapabilitiesoftheradioarethesame.Aperso

40、ndrivingacarwithoutaradiocanstilldrive,butcannothearmusic.Inacarthatdoeshavearadio,theradiointerfaceisavailable.COMsupportsthissamesortofmodelforCOMclasses.ACOMobjectcansupportacollectionofinterfaces,eachofwhichhasaname.ForCOMobjectsthatyoucreateyourself,youwilloftendefineandusejustasingleCOMinterfa

41、ce.ButmanyexistingCOMobjectssupportmultipleCOMinterfacesdependingonthefeaturestheysupport.Anotherimportantdistinctionisthatthedrivinginterfaceisnotthecar.Thedrivinginterfacedoesnttellyouanythingaboutthebrakes,orthewheels,ortheengineofthecar.Youdontdrivetheengineforexample,youusethefasterandslowermet

42、hods(acceleratorandbrakes)ofthedrivinginterface.Youdontreallycarehowtheslower(brake)methodisimplemented,aslongasthecarslowsdown.Whetherthecarhashydraulicorairbrakesisntimportant.ImagineacomponentWhenyourebuildingaCOMobject,youareveryconcernedabouthowtheinterfaceworks.Theuseroftheinterfacehowever,sho

43、uldntbeconcernedaboutitsimplementation.1.ikethebrakesonacar,theusercaresonlythattheinterfaceworks,notaboutthedetailsbehindtheinterface.ThisisolationofinterfaceandimplementationiscrucialforCOM.Byisolatingtheinterfacefromitsimplementation,wecanbuildcomponents.Componentscanbereplacedandre-used.Thisboth

44、simplifiesandmultipliestheusefulnessoftheobject.Whatsinaname?OneimportantfacttorecognizeisthatanamedCOMinterfaceisunique.Thatis,aprogrammerisallowedtomakeanassumptioninCOMthatifheaccessesaninterfaceofaspecificname,thememberfunctionsandparametersofthatinterfaceW川beexactlythesameinallCOMobjectsthatimp

45、lementtheinterface.So,followingourexample,theinterfacesnameddrivingandradiowillhaveexactlythesamememberfunctionsignatureinanyCOMobjectthatimplementsthem.Ifyouwanttochangethememberfunctionsofaninterfaceinanywaytyouhavetocreateanewinterfacewithanewname.Thesourceofallinterfaces-IUnknownTraditionalexpla

46、nationsofCOMstartoutwithathoroughdescriptionofthe(Unknowninterface.!UnknownisthefundamentalbasisforallCOMinterfaces.Despiteitsimportance,youdontneedtoknowabout!Unknowntounderstandtheinterfaceconcept.Theimplementationof!UnknownishiddenbythehigherlevelabstractionswellbeusingtobuildourCOMobjects.Actual

47、ly,payingtoomuchattentionto!Unknowncanbeconfusing.1.etsdealwithitatahighlevelheresoyouunderstandtheconcepts.(UnknownislikeanabstractbaseclassinC+.AllCOMinterfacesmustinheritfromIUnknown.!Unknownhandlesthecreationandmanagementoftheinterface.Themethodsof!Unknownareusedtocreate,referencecount,andreleas

48、eaCOMobject.AllCOMinterfacesimplementthese3methodsandtheyareusedinternallybyCOMtomanageinterfaces.Youwilllikelynevercallthese3methodsyourself.AtypicalCOMobjectNowletsputallofthesenewconceptstogetheranddescribeatypicalCOMobjectandaprogramthatwantstoaccessit.Inthenextsectionandthefollowingchapterswewillmakethisrealbyimplementingtheactualcodefortheobject.ImaginethatyouwanttocreatethesimplestpossibleCOMobject.Thisobjectwillsupportasingleinterface,andthatinterfacewillcontainasin

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 在线阅读 > 生活休闲


备案号:宁ICP备20000045号-1

经营许可证:宁B2-20210002

宁公网安备 64010402000986号