Upload
miguel-rhodes
View
229
Download
3
Tags:
Embed Size (px)
Citation preview
Component Object ModelComponent Object Model
Component Object ModelComponent Object Model
ActiveX and OLE rest on the foundation ActiveX and OLE rest on the foundation of COMof COM
Understanding COM is a prerequisite to Understanding COM is a prerequisite to understanding anything else in ActiveX understanding anything else in ActiveX or OLEor OLE
ComponentsComponents
Benefits of Components – Benefits of Components – FlexibilityFlexibility
Program for User A Program for User B
Benefits of Components – Benefits of Components – Component LibrariesComponent Libraries
Component Libraries New Program
Benefits of COM – Distributed Benefits of COM – Distributed ComponentsComponents
Network
Component Object ModelComponent Object Model
How should one chunk of software How should one chunk of software access the services provided by access the services provided by another chunk of software?another chunk of software?
COM: A standard approach to access COM: A standard approach to access all kinds of software services, all kinds of software services, regardless of how they are providedregardless of how they are provided
COM is transforming the way software COM is transforming the way software is constructedis constructed
Benefits of COMBenefits of COM Offers the benefits of object orientationOffers the benefits of object orientation Provides consistencyProvides consistency Is language independentIs language independent
COM defines a binary interface that objects COM defines a binary interface that objects must supportmust support
Simple and efficient versioningSimple and efficient versioning Available on Windows, Windows NT, Macintosh, Available on Windows, Windows NT, Macintosh,
MVS up to nowMVS up to now DCOM allows COM objects on all kinds of DCOM allows COM objects on all kinds of
systems to interactsystems to interact
Communications between Communications between SoftwareSoftware
OS
Applicationlib
Application
OS
Application
Basic COM ConceptBasic COM Concept
Binary Code of aServer Class
Interface
Interface
Interface
Binary Code of a Client Class
COMLibrary
Basic COM ConceptBasic COM Concept
COM object
Server
Interface
Interface
Interface
Basic COM ConceptBasic COM Concept
COM object
Client
Basic COM ConceptBasic COM Concept
OS
OS
Application
Application libApplication
A COM ObjectA COM Object
COM ObjectTextTools
Client
LookUpWord( )AddToDictionary( )
RemoveFromDictionary( )
ReturnSynonym( )
Identifying an InterfaceIdentifying an Interface Human-readable nameHuman-readable name
ISpellChecker, IThesaursISpellChecker, IThesaurs Globally Unique Identifier (GUID)Globally Unique Identifier (GUID) Interface Identifier (IID)Interface Identifier (IID) Each GUID is unique in time and spaceEach GUID is unique in time and space
TimestampTimestampAddress on the machine’s network interfacAddress on the machine’s network interfac
e carde card16 bits16 bits
GUID GeneratorGUID Generator
Interface Definition LanguageInterface Definition Language
[ object, uuid([ object, uuid( E7CD0D00-1827-11CF- E7CD0D00-1827-11CF- 9946444553540000) ]9946444553540000) ]interface ISpellChecker : IUnknown{interface ISpellChecker : IUnknown{
import “unknown.idl”;import “unknown.idl”;HRESULT LookUpWord(HRESULT LookUpWord(
[in] OLECHAR word[31],[in] OLECHAR word[31],[out] boolean *found );[out] boolean *found );
HRESULT AddToDictionary(HRESULT AddToDictionary([in] OLECHAR word[31]);[in] OLECHAR word[31]);
HRESULT RemoveFromDictionary(HRESULT RemoveFromDictionary([in] OLECHAR word[31]);[in] OLECHAR word[31]);
}}
Immutability of the InterfacesImmutability of the Interfaces Once an interface has been implemented Once an interface has been implemented
in released software, it cannot be changedin released software, it cannot be changed To add new functionality or to modify To add new functionality or to modify
existing functionality requires defining an existing functionality requires defining an entirely new interface, with a new and entirely new interface, with a new and different IIDdifferent IID
The creator of the software is free to stop The creator of the software is free to stop supporting the original interface but is supporting the original interface but is absolutely prohibited from changing itabsolutely prohibited from changing it
New Version ProblemNew Version Problem A COM object that supports ISpellCheckerA COM object that supports ISpellChecker Add support for a thesaurus function througAdd support for a thesaurus function throug
h IThesaurush IThesaurus Effect on the client using the old version witEffect on the client using the old version wit
h the old or new version installedh the old or new version installed Effect on the client using the new version wiEffect on the client using the new version wi
th the new version installedth the new version installed Effect on the client using the new version wiEffect on the client using the new version wi
th the old version installedth the old version installed
Changing Features to an Changing Features to an InterfaceInterface
The object’s creator must define a new interThe object’s creator must define a new interface, say ISpellChecker2 that includes the face, say ISpellChecker2 that includes the new or changed methods and the COM objnew or changed methods and the COM object continues to support ISpellChecker as bect continues to support ISpellChecker as before, but it now also support ISpellCheckerefore, but it now also support ISpellChecker22
Clients that are unaware of the upgrade neClients that are unaware of the upgrade never ask for a pointer to ISpellChecker2 and ver ask for a pointer to ISpellChecker2 and so aren’t affected by the changes – they coso aren’t affected by the changes – they continue to use ISpellChecker as beforentinue to use ISpellChecker as before
IUnknown::QueryInterfaceIUnknown::QueryInterface
COM objectClient
1
2
3
A
B
Reference CountingReference Counting Whenever the object passes out a pointer to onWhenever the object passes out a pointer to on
e of its interface, it adds 1 to reference count. Ie of its interface, it adds 1 to reference count. If one client passes an interface pointer to anothf one client passes an interface pointer to another client, the client who receives the pointer muer client, the client who receives the pointer must invoke the AddRef method using that pointerst invoke the AddRef method using that pointer
The client must call Release on the interface poThe client must call Release on the interface pointer to decrement the reference count when it inter to decrement the reference count when it has finished using the interfacehas finished using the interface
An object destroys itself when its reference couAn object destroys itself when its reference count drops to 0nt drops to 0
Binary Format of an InterfaceBinary Format of an Interface
AddRef( ) {…}
QueryInterface( ) {…}
LookUpWord( ) {…}
AddToDictionary( ) {…}
Release( ) {…}
RemoveFromDictionary( ) {…}
Pointer to Method 1
Pointer to Method 6
Pointer to Method 2
Pointer to Method 3
Pointer to Method 4
Pointer to Method 5
Client
Object
vtable
COM ClassesCOM Classes Class identifier (CLSID) Class identifier (CLSID) An object of a specific class supports a An object of a specific class supports a
certain set of interfacescertain set of interfaces Adding interfaces to an object without Adding interfaces to an object without
changing its class is not prohibited by COMchanging its class is not prohibited by COM An object’s class identifies a particular An object’s class identifies a particular
implementation of a group of interfacesimplementation of a group of interfaces It’s possible to have many classes It’s possible to have many classes
supporting the same set of interfacessupporting the same set of interfaces
Kinds of COM ServersKinds of COM Servers
Machine XMachine Y
COM LibraryCOM LibraryThe COM library implements a group of The COM library implements a group of
functions that supply basic services to ofunctions that supply basic services to objects and their clientsbjects and their clients
The COM library’s services are accesseThe COM library’s services are accessed through ordinary function callsd through ordinary function calls
The names of COM library functions usThe names of COM library functions usually begin with the prefix Co- for exampually begin with the prefix Co- for example, CoCreateInstancele, CoCreateInstance
System RegistrySystem Registry The classes of all objects that the COM The classes of all objects that the COM
library will be asked to create on this library will be asked to create on this machine must be registeredmachine must be registered
Registry mapping includesRegistry mapping includesCLSIDCLSIDKinds of serversKinds of serversPathname for the file containing the Pathname for the file containing the
server’s DLL or executable, or for where server’s DLL or executable, or for where to find remote server’s executableto find remote server’s executable
Creating a Single ObjectCreating a Single Object
Client
COMlibrary
Object
Server
CLSID_X
……
CLSID_Y
DLL
EXE
1 23
4
Class FactoriesClass FactoriesClass factory is a kind of objects that caClass factory is a kind of objects that ca
n create objects of one specific classn create objects of one specific classClass factories are COM objects in their Class factories are COM objects in their
own right – accessed via their interfacesown right – accessed via their interfacesCoCreateInstance uses a class factory tCoCreateInstance uses a class factory t
hat it hides from the clienthat it hides from the clientCoCreateInstance uses the methods in tCoCreateInstance uses the methods in t
he IClassFactory interfacehe IClassFactory interface
IClassFactory InterfaceIClassFactory InterfaceAs a class factory, an object must suppAs a class factory, an object must supp
ort the IClassFactory interfaceort the IClassFactory interface IClassFactoryIClassFactory
CreateInstanceCreateInstanceLockServerLockServer
IClassFactory2IClassFactory2A client calls CoGetClassObject to get a A client calls CoGetClassObject to get a
pointer to a class factorypointer to a class factory
Using Class FactoryUsing Class Factory
Client
ClassFactory
Object
Server
1
23
4
EmulationEmulation An old class is replaced by a new class wAn old class is replaced by a new class w
ith different CLSIDith different CLSID A COM library function CoTreatAsClass:A COM library function CoTreatAsClass: when used to create an object using the when used to create an object using the
old CLSID will result in instantiating an oold CLSID will result in instantiating an object with the new CLSIDbject with the new CLSID(setting up an emulation relationship bet(setting up an emulation relationship between the two CLSIDs in the system regisween the two CLSIDs in the system registry)try)
Initializing COM ObjectsInitializing COM ObjectsA client usually asks a newly created A client usually asks a newly created
objects to initialize itselfobjects to initialize itselfThe object’s data must be stored in a The object’s data must be stored in a
persistent waypersistent wayThe first interface pointer a client The first interface pointer a client
requests when a new object is created requests when a new object is created is usually the one for an interface is usually the one for an interface containing the object’s initialization containing the object’s initialization functionfunction
Calling Sequence in VC++ Calling Sequence in VC++ (1/2)(1/2)
CLSID clsid;CLSID clsid;
IClassFactory* pClf;IClassFactory* pClf;
IUnknown* pUnk;IUnknown* pUnk;
CoInitialize(NULL);CoInitialize(NULL);
::CLSIDFromProgID(L“TestTools”, &clsid);::CLSIDFromProgID(L“TestTools”, &clsid);
::CoGetClassObject(clsid, IID_IClassFactory, ::CoGetClassObject(clsid, IID_IClassFactory,
(void**) &pClf);(void**) &pClf);
Calling Sequence in VC++ Calling Sequence in VC++ (2/2)(2/2)
pClf->pClf->CreateInstance(IID_Iunknown, (void**)&pUnk);CreateInstance(IID_Iunknown, (void**)&pUnk);
pUnk->pUnk->QueryInterface(IID_ISpellChecker, (void**)&pSpQueryInterface(IID_ISpellChecker, (void**)&pSpl);l);
pSpl->LookUpWord( “Test”, found );pSpl->LookUpWord( “Test”, found );pClf->Release();pClf->Release();pUnk->Release();pUnk->Release();pSpl->Release();pSpl->Release();CoFreeUnusedLibraries();CoFreeUnusedLibraries();CoUninitialize();CoUninitialize();
Reusing COM ObjectsReusing COM ObjectsOne COM object can’t reuse another’s One COM object can’t reuse another’s
code through inheritancecode through inheritanceContainment (delegation)Containment (delegation)
AggregationAggregation
Marshaling and Type Marshaling and Type InformationInformation
Marshaling makes that the client can Marshaling makes that the client can invoke the methods in the same way, invoke the methods in the same way, regardless of where the object is regardless of where the object is implementedimplemented
To acquire the information necessary to To acquire the information necessary to perform marshaling, and sometimes for perform marshaling, and sometimes for other reasons as well, it can be useful to other reasons as well, it can be useful to obtain type information about the projectobtain type information about the project
Accessing a COM Object in an Accessing a COM Object in an In-Process ServerIn-Process Server
Client Object
Client process
Accessing a COM Object in a Accessing a COM Object in a Local ServerLocal Server
Proxy ObjectClient Stub
Client process Server Process
Single machine
Accessing a COM object in a Accessing a COM object in a Remote ServerRemote Server
Proxy ObjectClient Stub
Client process Server Process
Machine X Machine Y
Marshaling and UnmarshalingMarshaling and Unmarshaling MarshalingMarshaling
Packaging a call’s parameters into a standard format fPackaging a call’s parameters into a standard format for transmissionor transmission
UnmarshalingUnmarshalingUnpackaging from the standard format into a format apUnpackaging from the standard format into a format ap
propriate for the receiving processpropriate for the receiving process Marshaling Code (Marshaler)Marshaling Code (Marshaler) MIDL compiler can read the IDL description of an iMIDL compiler can read the IDL description of an i
nterface and automatically generate the necessarnterface and automatically generate the necessary marshalling code for this interface, contained in y marshalling code for this interface, contained in a proxy and a stuba proxy and a stub
Type InformationType InformationType information includes a description Type information includes a description
of everything a client needs to know to of everything a client needs to know to use an object’s service. For example, use an object’s service. For example, the type information of an object the type information of an object includes a list of the interface’s methods includes a list of the interface’s methods and properties, along with a description and properties, along with a description of the parameters for those methods.of the parameters for those methods.
All type information today should be All type information today should be defined using IDLdefined using IDL
Type LibraryType LibraryInterface and
Library definitionsIn IDL
MIDLcompiler
Proxies Stubs Type library Other files
IDL ExampleIDL Example[ object,uuid([ object,uuid( E7CD0D00-1827-11CF-9946-E7CD0D00-1827-11CF-9946- 444553540000) ]444553540000) ]interface ISpellChecker : IUnknown{interface ISpellChecker : IUnknown{
import “unknown.idl”;import “unknown.idl”;HRESULT LookUpWord(HRESULT LookUpWord(
[in] OLECHAR word[31],[in] OLECHAR word[31],[out] boolean *found );[out] boolean *found );
HRESULT AddToDictionary(HRESULT AddToDictionary([in] OLECHAR word[31]);[in] OLECHAR word[31]);
HRESULT RemoveFromDictionary(HRESULT RemoveFromDictionary([in] OLECHAR word[31]);[in] OLECHAR word[31]);
}}
IDL ExampleIDL Example[ object,uuid([ object,uuid(
5FBDD020-1863-11CF-9946-444553540000) ]5FBDD020-1863-11CF-9946-444553540000) ]
interface IThesaurus : IUnknown {interface IThesaurus : IUnknown {
HRESULT Return Synonym(HRESULT Return Synonym(
[in] OLECHAR word[31],[in] OLECHAR word[31],
[out] OLECHAR synonym[31] );[out] OLECHAR synonym[31] );
}}
IDL ExampleIDL Example[uuid( [uuid(
B253E460-1826-11CF-9946-444553540000), versionB253E460-1826-11CF-9946-444553540000), version(1.0)](1.0)]
library TextToolsLib {library TextToolsLib {importlib (“stdole32.tlb”);importlib (“stdole32.tlb”);[uuid([uuid(B2ECFAA0-1827-11CF-9946-444553540000)]B2ECFAA0-1827-11CF-9946-444553540000)]coclass CoTextTools {coclass CoTextTools {
interface ISpellChecker;interface ISpellChecker;interface IThesaurus;interface IThesaurus;
}}}}
AutomationAutomation Making applications programmableMaking applications programmable Programmability through macro languagesProgrammability through macro languages
CrypticCrypticNo standard existsNo standard existsOne choice for an applicationOne choice for an application
AutomationAutomationGeneral programmability with COMGeneral programmability with COMUse developer’s favorite programming tools to Use developer’s favorite programming tools to
build applications on top of the functions already build applications on top of the functions already provided by existing softwareprovided by existing software
Automation ExampleAutomation Example
Database
Spreadsheet
Word processor
Charting
Automation script:Extract current dataTabulate and sumChart the results
Place chart in reportSend electronic copies
of report to staff
IDispatch and dispinterfacesIDispatch and dispinterfaces
Client
Invoke( ) { switch (DISPID)1: MethodX( );2: MethodY( );3: MethodZ( );
}
IDispatch::Invoke(DISPID)
IDispatchvtable
Object
dispinterface
Clients and ServersClients and Servers
Client
Object
Object
ApplicationIDispatch
IDispatch
IServices
IDispatch
dispinterfaces and Marshalingdispinterfaces and Marshaling Using a dispinterface for marshaling requires onUsing a dispinterface for marshaling requires on
ly a single proxy and stubly a single proxy and stub The parameters for a dispinterface method are The parameters for a dispinterface method are
packaged into a variantpackaged into a variant The client passes the variant along with the DISThe client passes the variant along with the DIS
PID on the call to IDispatch::InvokePID on the call to IDispatch::Invoke The object that implements the dispinterface unThe object that implements the dispinterface un
packages the variant packages the variant Results are wrapped in a variant by the object aResults are wrapped in a variant by the object a
nd then returned to and unwrapped by the clientnd then returned to and unwrapped by the client
A Visual Basic ExampleA Visual Basic ExampleSub SpellCheck( )Sub SpellCheck( )
Dim Obj As ObjectDim Obj As ObjectSet Obj = CreateObject(“Excel.Application”)Set Obj = CreateObject(“Excel.Application”)Word = InputBox(“Enter word”)Word = InputBox(“Enter word”)If Obj.CheckSpelling(Word) ThenIf Obj.CheckSpelling(Word) Then
MsgBox( “Valid word” )MsgBox( “Valid word” )ElseElse
MsgBox( “Word not found” )MsgBox( “Word not found” )End IfEnd If
End SubEnd Sub
Dual InterfacesDual Interfaces
Client
Invoke( ) { switch (DISPID)1: MethodX( );2: MethodY( );3: MethodZ( );
}
IDispatch::Invoke(DISPID)
vtable
Object
dispinterface
Dual InterfacesDual Interfaces[object, uuid( E7CD0D00-1301-11CF- [object, uuid( E7CD0D00-1301-11CF- 9946-444553540000), dual]9946-444553540000), dual]Interface ISpellChecker : IDispatch Interface ISpellChecker : IDispatch {{
import “unknown.idl”;import “unknown.idl”;import “oaidl.idl”;import “oaidl.idl”;HRESULT LookUpWord([in] BSTR word,HRESULT LookUpWord([in] BSTR word,
[out] boolean *found);[out] boolean *found);HRESULT AddToDictionary(HRESULT AddToDictionary(
[in] BSTR word);[in] BSTR word);HRESULT RemoveFromDictionary(HRESULT RemoveFromDictionary(
[in] BSTR word);[in] BSTR word);}}
Dual InterfacesDual Interfaces
[uuid([uuid(B623E460-1837-11CF-9946-444553540000), versionB623E460-1837-11CF-9946-444553540000), version(1.0)](1.0)]
library SpellCheckerLib {library SpellCheckerLib {importlib (“stdole32.tlb”);importlib (“stdole32.tlb”);
[uuid([uuid(B23EFAA0-1849-11CF-9946-444553540000)]B23EFAA0-1849-11CF-9946-444553540000)]coclass CoSpellChecker {coclass CoSpellChecker {
interface ISpellChecker;interface ISpellChecker;}}
}}
Persistence and MonikersPersistence and Monikers An object’s persistent data is information An object’s persistent data is information
about the object’s state that’s saved about the object’s state that’s saved between instantiations of the objectbetween instantiations of the object
A mechanism that lets objects store and A mechanism that lets objects store and retrieve their persistent data is called a retrieve their persistent data is called a persistence servicepersistence service
An object’s client typically controls when An object’s client typically controls when the object’s persistent data is loaded and the object’s persistent data is loaded and savedsaved
Structured StorageStructured Storage
Root storage
Storage
StorageStorage
StorageStream
Stream Stream
Stream Stream Stream Stream
Disk file(Compound file)
Using Structured StorageUsing Structured Storage
COM object
Stream Stream
Storage
MonikerMonikerA moniker is a name for a specific objecA moniker is a name for a specific objec
t instance, one particular combination of t instance, one particular combination of CLSID and persistent dataCLSID and persistent data
A moniker is an object that supports the A moniker is an object that supports the IMoniker interfaceIMoniker interface
Each moniker has its own persistent datEach moniker has its own persistent data, which contains everything the monikea, which contains everything the moniker needs to start and initialize the single or needs to start and initialize the single object instance the moniker identifiesbject instance the moniker identifies
Using a MonikerUsing a Moniker
Client
Moniker
Object
Server1
2
3
4
A
IMoniker