Вы находитесь на странице: 1из 63

Component Object

Model

Shyh-Kang Jeng
Department of Electrical
Engineering/
Graduate Institute of Communication
Engineering
National Taiwan University
1
References
• D. Chappell, Understanding ActiveX an
d OLE, Microsoft Press, 1996.
• D. Rogerson 原著 , 黃昕暐編譯 , 完全剖析
COM, 華彩軟體 , 2000.
• D. J. Kruglinski, Inside Visual C++, Mic
rosoft Press, 1995.
• T. L. Thai, Learning DCOM, O’Reilly, 19
99.
• A. Denning 原著 , 侯俊傑譯 , OLE 控制元件
徹底研究 , 松崗 , 1996.

2
Component Object
Model
• ActiveX and OLE rest on the
foundation of COM
• Understanding COM is a
prerequisite to understanding
anything else in ActiveX or OLE

3
Components

4
Benefits of Components –
Flexibility

Program for User A Program for User B

5
Benefits of Components –
Component Libraries

Component Libraries New Program

6
Benefits of COM –
Distributed Components

Network

7
Component Object
Model
• How should one chunk of software
access the services provided by
another chunk of software?
• COM: A standard approach to
access all kinds of software
services, regardless of how they
are provided
• COM is transforming the way
software is constructed

8
COM is not…

• COM is not a programming


language
• COM is not DLL
• COM is not only a set of API or
functions
• COM is not a library

9
COM is…
• with the benefits of object
orientation
• with consistency
• language independent
• COM defines a binary interface that
objects must support
• with simple and efficient versioning
• available on Windows, Windows NT,
Macintosh, MVS up to now

10
Communications
between Software
lib
Application Application

Application OS

OS

11
Basic COM Concept
Interface

Interface
Binary Code of COM
a Client Class Library
Interface

Binary Code of a
Server Class

12
Basic COM Concept

Interface
Interface
COM object
Interface

Server

13
Basic COM Concept

COM object
Client

14
Basic COM Concept
Application lib
Application

Application

OS

OS

15
A COM Object
LookUpWord( )
AddToDictionary( )
RemoveFromDictionary( )

COM Object
TextTools
Client

ReturnSynonym( )

16
Identifying an Interface
• Human-readable name
• ISpellChecker, IThesaurs
• Globally Unique Identifier (GUID)
• Interface Identifier (IID)
• Each GUID is unique in time and space
• Timestamp
• Address on the machine’s network in
terface card
• 16 bytes (128 bits)

17
GUID Generator

18
Using GUID Generator
• Add To Project…
| Components
and Controls… |
Visual C++
Components |
GUID Generator
• More Info
• Insert | Copy

19
Interface Definition
Language
[ object, uuid(
E7CD0D00-1827-11CF-
9946444553540000) ]
interface ISpellChecker : IUnknown{
import “unknown.idl”;
HRESULT LookUpWord(
[in] OLECHAR word[31],
[out] boolean *found );
HRESULT AddToDictionary(
[in] OLECHAR word[31]);
HRESULT RemoveFromDictionary(
[in] OLECHAR word[31]);
}

20
Immutability of the
Interfaces
• Once an interface has been implemented
in released software, it cannot be
changed
• To add new functionality or to modify
existing functionality requires defining
an entirely new interface, with a new
and different IID
• The creator of the software is free to
stop supporting the original interface but
is absolutely prohibited from changing it

21
New Version Problem
• A COM object that supports ISpellChec
ker
• Add support for a thesaurus function th
rough IThesaurus
• Effect on the client using the old versio
n with the old or new version installed
• Effect on the client using the new versi
on with the new version installed
• Effect on the client using the new versi
on with the old version installed

22
Changing Features to an
Interface
• The object’s creator must define a new
interface, say ISpellChecker2 that inclu
des the new or changed methods and th
e COM object continues to support ISpe
llChecker as before, but it now also sup
port ISpellChecker2
• Clients that are unaware of the upgrade
never ask for a pointer to ISpellChecker
2 and so aren’t affected by the changes
– they continue to use ISpellChecker as
before

23
IUnknown::QueryInterface

1
A

2 COM object
Client

B
3

24
Reference Counting
• Whenever the object passes out a pointer
to one of its interface, it adds 1 to referen
ce count. If one client passes an interfac
e pointer to another client, the client who
receives the pointer must invoke the AddR
ef method using that pointer
• The client must call Release on the interfa
ce pointer to decrement the reference cou
nt when it has finished using the interface
• An object destroys itself when its referenc
e count drops to 0

25
Binary Format of an
Interface
Object
QueryInterface( ) {…}
Client
Pointer to Method 1
AddRef( ) {…}
Pointer to Method 2
Release( ) {…}
Pointer to Method 3
LookUpWord( ) {…}
Pointer to Method 4

Pointer to Method 5 AddToDictionary( ) {…}

Pointer to Method 6 RemoveFromDictionary( ) {…}


vtable
26
COM Classes
• Class identifier (CLSID)
• An object of a specific class supports a
certain set of interfaces
• Adding interfaces to an object without
changing its class is not prohibited by
COM
• An object’s class identifies a particular
implementation of a group of interfaces
• It’s possible to have many classes
supporting the same set of interfaces

27
Kinds of COM Servers

Machine X
Machine Y

28
COM Library
• The COM library implements a group
of functions that supply basic servic
es to objects and their clients
• The COM library’s services are acce
ssed through ordinary function calls
• The names of COM library functions
usually begin with the prefix Co- for
example, CoCreateInstance

29
System Registry
• The classes of all objects that the COM
library will be asked to create on this
machine must be registered
• Registry mapping includes
• CLSID
• Kinds of servers
• Pathname for the file containing the
server’s DLL or executable, or for
where to find remote server’s
executable

30
Creating a Single Object

4
Client Object

Server
1 3
2
CLSID_X DLL
COM
library CLSID_Y EXE
……
31
Class Factories
• Class factory is a kind of objects that
can create objects of one specific clas
s
• Class factories are COM objects in thei
r own right – accessed via their interfa
ces
• CoCreateInstance uses a class factory
that it hides from the client
• CoCreateInstance uses the methods in
the IClassFactory interface

32
IClassFactory Interface
• As a class factory, an object must
support the IClassFactory interfac
e
• IClassFactory
• CreateInstance
• LockServer
• IClassFactory2
• A client calls CoGetClassObject to
get a pointer to a class factory

33
Using Class Factory
4
Client Object

3 2

1 Class
Factory

Server
34
Emulation
• An old class is replaced by a new clas
s with different CLSID
• A COM library function CoTreatAsClas
s:
when used to create an object using t
he old CLSID will result in instantiatin
g an object with the new CLSID
(setting up an emulation relationship
between the two CLSIDs in the syste
m registry)

35
Initializing COM Objects
• A client usually asks a newly
created objects to initialize itself
• The object’s data must be stored
in a persistent way
• The first interface pointer a client
requests when a new object is
created is usually the one for an
interface containing the object’s
initialization function

36
Calling Sequence in VC+
+ (1/2)
CLSID clsid;
IClassFactory* pClf;
IUnknown* pUnk;
CoInitialize(NULL);
::CLSIDFromProgID(L“TextTools”, &clsid);
::CoGetClassObject(clsid, IID_IClassFactory,
(void**) &pClf);

37
Calling Sequence in VC+
+ (2/2)
pClf->
CreateInstance(IID_IUnknown, (void**)&pUnk);
pUnk->
QueryInterface(IID_ISpellChecker, (void**)&pSp
l);
pSpl->LookUpWord( “Test”, found );
pClf->Release();
pUnk->Release();
pSpl->Release();
CoFreeUnusedLibraries();
CoUninitialize();

38
Reusing COM Objects
• One COM object can’t reuse
another’s code through
inheritance
• Containment (delegation)

• Aggregation

39
Marshaling and Type
Information
• Marshaling makes that the client can
invoke the methods in the same way,
regardless of where the object is
implemented
• To acquire the information
necessary to perform marshaling,
and sometimes for other reasons as
well, it can be useful to obtain type
information about the project

40
Accessing a COM Object
in an In-Process Server

Client Object

Client process

41
Accessing a COM Object
in a Local Server

Proxy Stub Object


Client
Client process Server Process

Single machine

42
Accessing a COM object
in a Remote Server

Proxy Stub Object


Client
Client process Server Process

Machine X Machine Y

43
Marshaling and Unmarsh
aling
• Marshaling
• Packaging a call’s parameters into a standard f
ormat for transmission
• Unmarshaling
• Unpackaging from the standard format into a f
ormat appropriate for the receiving process
• Marshaling Code (Marshaler)
• MIDL compiler can read the IDL descriptio
n of an interface and automatically genera
te the necessary marshalling code for this
interface, contained in a proxy and a stub

44
Type Information
• Type information includes a
description of everything a client
needs to know to use an object’s
service. For example, the type
information of an object includes a
list of the interface’s methods and
properties, along with a description
of the parameters for those methods.
• All type information today should be
defined using IDL

45
Type Library
Interface and
Library definitions
In IDL

MIDL
compiler

Proxies Stubs Type library Other files

46
IDL Example
[ object,uuid(
E7CD0D00-1827-11CF-9946- 444553540000) ]
interface ISpellChecker : IUnknown{
import “unknown.idl”;
HRESULT LookUpWord(
[in] OLECHAR word[31],
[out] boolean *found );
HRESULT AddToDictionary(
[in] OLECHAR word[31]);
HRESULT RemoveFromDictionary(
[in] OLECHAR word[31]);
}

47
IDL Example
[ object,uuid(
5FBDD020-1863-11CF-9946-444553540000) ]
interface IThesaurus : IUnknown {
HRESULT ReturnSynonym(
[in] OLECHAR word[31],
[out] OLECHAR synonym[31] );
}

48
IDL Example
[uuid(
B253E460-1826-11CF-9946-444553540000), version
(1.0)]
library TextToolsLib {
importlib (“stdole32.tlb”);
[uuid(
B2ECFAA0-1827-11CF-9946-444553540000)]
coclass CoTextTools {
interface ISpellChecker;
interface IThesaurus;
}
}

49
Automation
• Making applications programmable
• Programmability through macro
languages
• Cryptic
• No standard exists
• One choice for an application
• Automation
• General programmability with COM
• Use developer’s favorite programming tools to
build applications on top of the functions
already provided by existing software

50
Automation Example
Database Spreadsheet Charting

Automation script:
Extract current data Word processor
Tabulate and sum
Chart the results
Place chart in report
Send electronic copies E-mail
of report to staff

51
IDispatch and dispinterf
aces
Client Object

IDispatch::
dispinterface
Invoke(DISPID)
Invoke( ) { switch (DISPID)
1: MethodX( );
2: MethodY( );
3: MethodZ( );
IDispatch }
vtable

52
Clients and Servers

Application
Client IDispatch

Object
IServices

IDispatch
Object
IDispatch

53
dispinterfaces and Mars
haling
• Using a dispinterface for marshaling requir
es only a single proxy and stub
• The parameters for a dispinterface method
are packaged into a variant
• The client passes the variant along with th
e DISPID on the call to IDispatch::Invoke
• The object that implements the dispinterfa
ce unpackages the variant
• Results are wrapped in a variant by the obj
ect and then returned to and unwrapped b
y the client

54
A Visual Basic Example
Sub SpellCheck( )
Dim Obj As Object
Set Obj = CreateObject(“Excel.Application”)
Word = InputBox(“Enter word”)
If Obj.CheckSpelling(Word) Then
MsgBox( “Valid word” )
Else
MsgBox( “Word not found” )
End If
End Sub

55
Dual Interfaces

Client Object

IDispatch::
dispinterface
Invoke(DISPID)
Invoke( ) { switch (DISPID)
1: MethodX( );
2: MethodY( );
3: MethodZ( );
vtable }

56
Dual Interfaces
[object, uuid( E7CD0D00-1301-11CF-
9946-444553540000), dual]
Interface ISpellChecker : IDispatch {
import “unknown.idl”;
import “oaidl.idl”;
HRESULT LookUpWord([in] BSTR word,
[out] boolean *found);
HRESULT AddToDictionary(
[in] BSTR word);
HRESULT RemoveFromDictionary(
[in] BSTR word);
}

57
Dual Interfaces
[uuid(
B623E460-1837-11CF-9946-444553540000), version
(1.0)]
library SpellCheckerLib {
importlib (“stdole32.tlb”);

[uuid(
B23EFAA0-1849-11CF-9946-444553540000)]
coclass CoSpellChecker {
interface ISpellChecker;
}
}

58
Persistence
• An object’s persistent data is
information about the object’s state
that’s saved between instantiations
of the object
• A mechanism that lets objects store
and retrieve their persistent data is
called a persistence service
• An object’s client typically controls
when the object’s persistent data is
loaded and saved

59
Structured Storage
Disk file Root storage
(Compound file)

Storage Stream Storage

Stream Storage Stream Storage

Stream Stream Stream Stream

60
Using Structured
Storage
COM object

Storage

Stream Stream

61
Moniker
• A moniker is a name for a specific ob
ject instance, one particular combina
tion of CLSID and persistent data
• A moniker is an object that supports
the IMoniker interface
• Each moniker has its own persistent
data, which contains everything the
moniker needs to start and initialize t
he single object instance the monike
r identifies

62
Using a Moniker
4
Client
Object
A
Server
1 3

Moniker 2
IMoniker

63

Вам также может понравиться