Component Object Model


1. What is COM ?

- COM is an acronym for Component Object Model.

- Component Object Model (COM) is a binary-interface standard for software componentry introduced by Microsoft in 1993.

- Simply put, COM is a way of building objects that is independent of any programming language.


2. Why do we need COM ?

- COM allows reuse of objects with no knowledge of their internal implementation

- if software component has interface standard, any program can put interface to use it.


3. What is Benefit of COM ?

- It is used to enable interprocess communication and dynamic object creation in a large range of programming languages.


4. What is Component ?

- when separation of a single piece of software in the abstract conceptual

- a number of COM objects

- compiled binary


5. What is Benefit of Component

- Application Customizing, Easy to change of application


6. What are Client and Server in COM

- Client : Process which uses component

- Server : exe file or DLL is implemented as a Component



COM Interface


1. What is interface

- each software components that support COM take advantage of the capabilities through interface

- It is not a standard at the level of source code, but it is a standard at the level of binary level.

- Interface is virtual function table


struct IExample


virtual void FunctionA() = 0;

virtual void FunctionB() = 0;

- Interface is represented by attaching 'I' followed by the name of


- Interface is declared just by cover, doesn’t implement the contents of the function. The role of the interface isn’t implementation some features, that can be shared among different software components that define the shape is because of features.

- In other words, the interface has a different software components, functions as a link that allows you to share. Let’s do something in between calling and called to set an appointment.




- Microsoft has predefined more than 100 interfaces that any COM object can support. These interfaces are called standard interfaces. User-defined interfaces such as IMath and ISpelling are custom interfaces. COM objects can use standard interfaces, custom interfaces, or a combination of the two.



IUnKnown Interface


- All COM components must implement the standard IUnknown interface.

- The IUnknown interface consists of 3 methods: AddRef(), Release(), QueryInterface()


Method Name Description

QueryInterface            Returns a pointer to another interface

AddRef            Increments the object's reference count

Release          Decrements the object's reference count


- One of the rules of COM says that given a pointer to an interface, a client can call any IUnknown method through that pointer as well as any methods that are specific to the interface. In other words, all interfaces must support the three IUnknown methods in addition to their own methods. This means that if you define an IMath interface with methods named Add and Subtract, the interface actually contains five methods: QueryInterface, AddRef, Release, Add, and Subtract. Most objects don't implement IUnknown as a separate interface. Because all interfaces include the IUnknown methods, most objects, if asked for an IUnknown pointer, simply return a pointer to one of their other interfaces.



 The pic shows a schematic of a simple COM object. The sticks, or "lollipops" as they're sometimes called, represent the object's interfaces. The IUnknown lollipop is often omitted because it's understood that every COM object implements IUnknown.





- A COM component's interfaces are required to exhibit the reflexive, symmetric, transitive properties.


- Implementing IUnknown


IA * pA = (some function returning an IA *);

IB * pB = NULL;


hr = pA->QueryInterface(IID_IB, &pB); // line 4


The reflexive property

The reflexive property refers to the ability for the QueryInterface() call on a given interface with the interface's ID to return the same instance of the interface.

The symmetric property

The symmetric property requires that when interface B is retrieved from interface A via QueryInterface()

The transitive property

The transitive property requires that if interface B is obtained from interface A and interface C is obtainable from interface B, then interface C should be retrievable  from interface A


- Object  Lifetimes

C++ programmers are used to creating heap-based objects using the C++ new operator. They're also accustomed to calling delete to delete the objects that they create with new. COM differs from C++ in this respect, because clients create object instances but they don't delete them. Instead, COM objects delete themselves. Here's why.


Suppose two or more clients are using the same instance of an object. Client A creates the object, and Client B attaches to the object by somehow acquiring an interface pointer. If Client A, unaware that Client B exists, deletes the object, Client B is left with an interface pointer that no longer points to anything. Because a COM client typically doesn't know (and doesn't care) whether it's the sole user of an object or one of many users, COM leaves it up to the object to delete itself. Deletion occurs when an internal reference count maintained by the object drops to 0. The reference count is a running count of the number of clients holding pointers to the object's interfaces.


For COM classes implemented in C++, the reference count is typically stored in a member variable. The count is incremented when AddRef is called and decremented when Release is called. (Remember that because AddRef and Release are IUnknown methods, they can be called through any interface pointer.) Implementations of AddRef and Release are normally no more complicated than this:





- One or more of the interface and the interface code that refers to the actual implementation.
Either alone or together many more are stored in the form of a DLL or EXE file

- CoClass methods

- AddRef() : increase 1 of reference counter

- Release() : decrease 1 of reference counter

- QueryInterface() : get interface’s pointer. QueryInterface must have stable behavior: If it succeeds once for a particular interface on a particular instance, it should always succeed

- User-Defined method : Implement the function


- COM Object : CoClass is created in memory after instantiation

- COM Server : one or more of the CoClass is created and DLL or EXE file that is stored in the unit

- COM Client : Software which using COM server’s functions

- In other to exec Program, have to know the file name or ID. CoClass use GUID instead of using file name. GUID is Identifiers and is called it IID for short. CLSID is CoClass’s Identifiers.  

-HRESULT : return value type of method which is used in COM, An HRESULT tells the caller whether a call succeeded or failed

- COM Library : COM is supported by the operating system from a series of related services


The following HRESULT values are the most common. More values are contained in the header file Winerror.h.


Here are the values listed alphabetically by name.

Name    Description    Value

S_OK    Operation successful   0x00000000

E_ABORT Operation aborted      0x80004004

E_ACCESSDENIED General access denied error    0x80070005

E_FAIL  Unspecified failure    0x80004005

E_HANDLE       Handle that is not valid       0x80070006

E_INVALIDARG   One or more arguments are not valid   0x80070057

E_NOINTERFACE  No such interface supported    0x80004002

E_NOTIMPL      Not implemented 0x80004001

E_OUTOFMEMORY  Failed to allocate necessary memory   0x8007000E

E_POINTER      Pointer that is not valid      0x80004003

E_UNEXPECTED   Unexpected failure     0x8000FFFF


Here are the values listed in numeric order by value.

Value   Name    Description

0x00000000     S_OK    Operation successful

0x80004001     E_NOTIMPL      Not implemented

0x80004002     E_NOINTERFACE  No such interface supported

0x80004003     E_POINTER      Pointer that is not valid

0x80004004     E_ABORT Operation aborted

0x80004005     E_FAIL  Unspecified failure

0x8000FFFF     E_UNEXPECTED   Unexpected failure

0x80070005     E_ACCESSDENIED General access denied error

0x80070006     E_HANDLE       Handle that is not valid

0x8007000E     E_OUTOFMEMORY  Failed to allocate necessary memory

0x80070057     E_INVALIDARG   One or more arguments are not valid


Class Factory


1. What is Class Factory

COM 라이브러리는 레지스트리에서 주어진 CLSID에 해당하는 CoClass가 어느 파일에 저장되어 있는지 알아내고, 그 파일을 메모리로 불러들이고, COM 오브젝트를 생성하여 이 COM 오브젝트에 속한 한 인터페이스의 포인터를 클라이언트에게 넘겨준다.

하지만 이 과정은 상당히 시간이 많이 걸리는 작업인 데, 이 복잡환 과정을 생략하여 훨씬 효율적인 방법이 바로 클래스 팩토리이다.


클래스 팩토리는 대표로 먼저 생성되어 다른 CoClass들의 인스턴스를 생성시켜주는 역할을 하는 CoClass를 말한다. 이 이름은 CoClass를 생성하는 공장 같은 역할을 한다는 의미로 붙여진 말인데, FMC는 이 일을 하는 클래스를 COleObjectFactory라는 이름으로 제공 하는데, CoClass가 메모리 상에 생성되어 인스턴스화 된 것을 COM 오브젝트라고 하기 때문에 붙여진 말이다.

사실, 클래스 팩토리라는 말보다 오브젝트 팩토리가 개념상 더 적합한 말이라고 할 수 있다.



- Class Factory is CoClass which has been created to represent firstly, and then help serve an instance of CoClass to be created.

The name of the CoClass is generated as a sign that acts as factories to produce CoClass.

In fact, object factory can be conceptually more appropriate to say then Class Factory.


'Computer Engineering > C++' 카테고리의 다른 글

Component Object Model  (0) 2012.01.11
[C++] Memory Leaks 메모리 누수  (0) 2011.12.21

What is a memory leak in C++ ?

A memory leak occurs when a piece (or pieces) of memory that was previously allocated by a programmer is not properly deallocated by the programmer. Even though that memory is no longer in use by the program, it is still “reserved”, and that piece of memory can not be used by the program until it is properly deallocated by the programmer. That’s why it’s called a memory leak – because it’s like a leaky faucet in which water is being wasted, only in this case it’s computer memory.

What problems can be caused by memory leaks?

The problem caused by a memory leak is that it leaves chunk(s) of memory unavailable for use by the programmer. If a program has a lot of memory that hasn’t been deallocated, then that could really slow down the performance of the program. If there’s no memory left in the program because of memory leaks, then that could of course cause the program to crash.

What is the difference between delete and delete[ ]?

The difference is big, and very important to understand. Whenever you create an object in C++ using the new keyword you will have to delete it. Whether you use “delete” or “delete[ ]” really depends on what kind of object you are creating.

This is best illustrated by an example:

void foo ( )
    string *sp = new string[50];
    string *s = new string;
    delete s;

    // have to use "[ ]" since sp points to an array of strings:
    delete[ ] sp;

we had to use the “[ ]” when deleting the memory that “sp” points to, because the sp pointer points to an array of strings.
So, in order to properly remove memory created with a “[ ]“, we have to use the “delete [ ] “.

Case1) An example of a memory leak in C++

(Pointer goes out of scope) Here is an example of a memory leak in C++:

void foo ()
  int *i = new int;
  *i = 44;


void foo()
  char* str = new char[20];
strcpy(str,"memory leak");

So, the problem with the code above is that the “*data” pointer is never deleted – which means that the data it references is never deallocated, and memory is wasted.

Case2) An example of a memory leak in C++

(Wrong usage of new/delete) Here is an example of a memory leak in C++:

void foo()
  double d1 = new double;
  double* d2 = new double[10];

  delete[] d1;
delete d2; // delete d[0];

This could create a memory leak since using “delete” when “delete[ ]” is required will not properly delete all of the memory in the array.

Case3) An example of a memory leak in C++

(Wrong usage of new/delete) Here is an example of a memory leak in C++:

void foo()
  int *i;
    i = new int;
    // some code
delete i;

In the end, one of pointers is deleted. But, it could make several issues. Before exiting a loop(‘WHILE block’), we have to make sure that each dynamic memory must be deleted.

Case4) An example of a memory leak in C++

("Lost" pointers) Here is an example of a memory leak in C++:

void foo()
  char* str1 = new char [30];
  char* str2 = new char [40];

  strcpy(str1, "Memory leak");

  str2 = str1; // Bad! Now the 40 bytes are impossible to free.

  delete [] str2; // This deletes the 30 bytes.
delete [] str1; // Possible access violation. What a disaster!

In this case, ‘str2’ lost its pointer in line 4 (str2 = str1), which means that the data(40bytes) it references is never freed, and memory is wasted.

Case5) An example of a memory leak in C++

("Lost" pointers) Here is an example of a memory leak in C++:

class Sample
  int* val;

    val = new int;
    *val = 44;

    delete val;

void foo()
  Sample* a = new Sample;
  Sample* b = new Sample;
  a = b;

  delete a; // actually deletes b

  //delete b; // already deleted

Same case as Case4

Case6) An example of a memory leak in C++

("Lost" pointers) Here is an example of a memory leak in C++:

void foo()
  char* str = new char [30]; // Give str a memory address.

  // delete [] str; // Remove the first comment marking in this line to correct.

  str = new char [60]; // Give str another memory address with the first one gone forever.

  delete [] str; // This deletes the 60 bytes, not just the first 30.

Same case as Case4

'Computer Engineering > C++' 카테고리의 다른 글

Component Object Model  (0) 2012.01.11
[C++] Memory Leaks 메모리 누수  (0) 2011.12.21

+ Recent posts