Tải bản đầy đủ - 0 (trang)
7 Using .NET Objects in COM

7 Using .NET Objects in COM

Tải bản đầy đủ - 0trang

namespaceDotNetObject

{



publicinterfaceIVehicle

{

intWheels

{

get;

set;

}

}



publicinterfaceIAirVehicle:IVehicle

{

intElevation

{

get;

set;

}



}



publicinterfaceIAirplane:IAirVehicle

{

intCapacity

{

get;

set;

}

}



publicclassAirplane:IAirplane

{

privateintcapacity,elevation,wheels;



publicAirplane()

{

capacity=200;



elevation=0;

wheels=4;

}



publicintCapacity

{

get

{

returnthis.capacity;

}

set

{

this.capacity=value;

}

}



publicintElevation

{

get



{

returnthis.elevation;

}

set

{

this.elevation=value;

}

}



publicintWheels

{

get

{

returnthis.wheels;

}

set

{

this.wheels=value;



}

}

}



publicclassNonInterfaceClass

{

publicvoidTest()

{



Console.WriteLine("NonInterfaceClass.Testsucceede

}

}

}

ThefirststeptoprepareyourassemblyforCOMinteropisto

generateastrongkey.COMuseslocationinformationwithinthe

RegistrytolocatethelibraryaCOMobjectexistsin.However,

whenyougeneratethetypelibraryshownlater,allthatis

generatedisthetypelibrarywithoutanassociatedCOMDLL.

TheCOMCallableWrapper(CCW)thatiscreatedwhenyour

COMobjectattemptstoinstantiatea.NETobjectiscontained

withintheCLR.Therefore,becausetheCOMobject'sfirstlineof

communicationiswiththeCLR,thelocationinformationpoints

totheMicrosoftCommonObjectRuntimeExecutionEngine

(mscoree.dll).Whatyouneedtodoistellthemscoree.dll

whereyourassemblyislocated,whichyoudobyassigninga



strongkeytoyourassemblybeforeyouexportthetypelibrary

(whichthisexampledemonstrates)orinstalltheassemblyinto

theGlobalAssemblyCache(GAC).

Togenerateastrongkeyname,whichyouneedtodoonly

once,openacommand-promptwindowandnavigatetoyour

.NETprojectdirectory.Next,runthestrong-keygeneration

programspecifyingthenameofthekeyfiletocreate:



sn.exekstrongKey.skn

ThislineassumesthattheVisualStudio.NETSDKisinyour

PATHenvironmentvariable.Ifnot,youcanopenacommand

promptusingthelinkintheToolsfolderofyourVisualStudio

.NET2003Startmenuprogramgroup.

Onceyougenerateastrongkey,youhavetosignyour

assembly.TheC#compilerdoesthisstepeachtimeyoubuild.

Tosigntheassembly,opentheAssemblyInfo.csfileand

changethefollowingline:



[assembly:AssemblyKeyFile("")]

Youaddthelocationofthekeyfile.Thislocationisrelativeto

thetargetdirectorywhereyourfinalassemblyisplaced,soyou

havetousearelativepathifyourstrongkeyfileiswithinyour



mainsourcedirectory:



[assembly:AssemblyKeyFile("../../strongKey.snk")]

Thelaststepissimilartothestepyouusedwhengeneratingan

interopassemblyforyour.NETobjectinRecipe24.2,"Using

COMObjectsin.NET."Additionally,wemakethisstep

automaticsoyoudon'thavetorepeattheprocesseachtime

youbuildyour.NETproject.ClickonProject,Propertiesfrom

themainmenuandselecttheCommonProperties,BuildEvents

propertypages.Inthepost-buildeventcommandline,enter

RegAsm.exeastheprogramtoexecute,passingasarguments

thelocationofyour.NETassembly,thelocationoftheresulting

typelibraryprefacedwiththetlb:switch,andthe/codebase

switch:



"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322/RegAsm.exe""$(T

/tlb:"$(TargetDir)\$(TargetName).tlb"/codebase

Inthiscommand,$(TargetPath)isthefullpathtothe.NET

assemblyand$(TargetDir)\$(TargetName).tlbcreatesa

typelibraryinthesamelocationastheassemblyandwiththe

samenamebutusinga.tlbfileextension.Thelastargument,

/codebase,helpsmscoree.dllfindyourassemblywhenaCOM

objectrequestsit.InkeepingwithCOMtradition,thecodebase



argumentplacesthefullpathtoyourassemblywithinthe

WindowsRegistry.

Atthispoint,younowhavea.NETassemblycontainingobjects

thataCOMclientcanuse.Thelaststeptocompletethis

exerciseistocreatetheCOMclient.CreateanewVisualC++

projectusingtheWin32ConsoleApplicationtemplate.When

theprojectopens,youseeonlytherequiredpartsforafull

C++application,whichisn'tmuch.Thefirststepistotellthe

compilerthatyouaregoingtouseanobjectcontainedwithin

anothertypelibrary.Youusethe#importkeyword.This

keywordissomewhatsimilartotheusingkeywordinC#,

althoughinternallydifferentinmanyways.Next,createa

methodcalledTestthatwillbeusedtotestthe.NETobjects,

asshowninthecodefollowingthisparagraph.Thefirstlineisa

variabledeclarationusing#import-generatedsmartpointers.

Explainingthesesmartpointersiswellbeyondthescopeofthis

book.Ingeneral,youarecreatinganinterfacepointerwhose

implementationiscontainedwithintheclassidentifiedbythe

CLSIDparameterintheconstructor.Thesetwoobjectsmapto

theIAirplaneinterfaceandAirplaneclass,respectively,

withinyour.NETclass.Atthispoint,theobjectiscreatedand

readyforuse.ThelasttwolinessimplysettheCapacity

propertyandthenprintoutthatpropertytotheconsole:



#include"stdafx.h"



#import"../7_NetClient/bin/Debug/DotNetObject.tlb"named_guids



voidTest()

{



DotNetObject::IAirplanePtrpAirplane(DotNetObject::CLSID_A

pAirplane->Capacity=500;

printf("AirplaneCapacity:%d\n",pAirplane->Capacity);

}



int_tmain(intargc,_TCHAR*argv[])

{

CoInitialize(NULL);

Test();

CoUninitialize();



return0;

}



Comments

Asmentionedrightatthebeginningofthisrecipe,makinga



.NETobjectCOMenabledisalotmoreinvolvedthantheother

wayaround.Eventhoughtheprocessisrelativelytrivialfrom

the.NETstandpoint,youstillhavetorearchitectyour

applicationtomakeextensiveuseofinterfacesifyouhaven't

alreadydoneso.BecauseCOMonlyusesinterfacemethods

whenaccessinganobject,youmustimplementinterfaceson

your.NETobjectifyoueverwantaCOMclienttohaveaccess.

Inmostcases,youcansimplytakea.NETclassandcreate

interfacesbasedoffexistingclassmembers.

Whenyour.NETobjectisinstantiatedbyaCOMobject,theCLR

createsaCCW,whichbehavessimilarlytotheRCWgoinginthe

otherdirection.CallsfromtheCOMclientarehandledinthe

proxyobjectcontainedwithintheCLR,andanynecessary

parametersaremarshaledintotheirequivalent.NETdatatypes

beforethefinalcallismadeonthe.NETobject.

Oneofthemainreasonsthatthismethodisalittlemore

involvedthancallingaCOMobjectfrom.NETconcerns

somethingknownasLocalServer32.WhenaCOMobjectis

registered,itslocationisplacedwithinauniqueidentifying

numberknownasaCLSID,whichisagloballyuniqueidentifier

(GUID).WithinthiskeyisasubkeycalledLocalServer32.In

mostcases,thisvalueisalocationtothebinaryfilehousingthe

COMobject.However,whenusingCOMinterop,thelocationis

pointingtomscoree.dll,therebylosinganyinformation

regardingthelocationoftheassemblywheretheobjectis

located.Tosolvethisproblem,youhavetotelltheCLRwhere

theassociatedassemblyislocated,eitherbyusingthe

/codebaseargumentfortheRegAsmtoolorbyinstallingthe

assemblyintotheGAC.



24.8ViewinganExported.NETTypeLibrary

Youwanttoviewtheresultingtypelibraryexportedfroma.NET

assembly.



Technique

JustasyouuseILDasm.exetoviewtypeinformationabouta

.NETassembly,youusetheOLE/COMObjectViewertoview

informationaboutatypelibrary.Youcanlaunchthetoolfrom

theToolsmenuwithinVisualStudio.NET.

Thetreecontrolontheleftsideofthetooltakesallthe

informationfromtheRegistryconcerningregisteredCOM

objectsandlogicallygroupsthatinformationbasedonitstype.

Forinstance,theTypeLibrariestreenodedisplaysalistof

registeredtypelibrariesusingthefriendlynameofthetype

library.TheInterfacestreenodedisplaysalltheknown

interfaceswithinthesystem.Wedon'trecommendexpanding

thatnodeonaslowcomputer.Youmighthavetowaitawhile.

Theeasiestwaytoviewthecontentsofatypelibrarywithout

havingtosearchthroughlistsistousetheViewTypelibmenu

itemontheFilemenu.Theexportedtypelibrarycreatedinthis

chapterforthe.NETobjectusesa.tlbextensionandislocated

inthesamedirectoryasthe.NETassembly.

Afteryouopenthetypelibrary,anotherwindowopens,listing

alltheavailableinterfaces,dispatchinterface,andco-classes.A

dispatchinterfaceissimplyaninterfacethatsupportsOLE

automationandtheIDispatchinterface.Wheneverscripting



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

7 Using .NET Objects in COM

Tải bản đầy đủ ngay(0 tr)

×