EQuestionAnswers.com Computer/Electronics Questions and Answers
C, C++, VC++, COM/DCOM, DLL and more
#Login #Sign up  Facebook Twitter TGoogle+
 

#Previous question #Index of COM/DCOM Questions #Next question

COM servers are distributed to the external users and developers. Developers can utilize COM server functionalities by accessing the interfaces. Microsoft Office, Internet explorer, Adobe Photoshop and many other components are reused in these ways. COM server is packaged in a DLL/OCX/EXE file and accompanied with .tlb type library file. C++ header interface files are given to C++ developer. COM server binaries are copied in System32 folder or Program Files/ folder. Visual Basic, Java Script, C#, VC++ can use the component or type library directly. C++ developer can optionally use the C++ header interfaces.

There are two approaches to develop a COM client in VC++/C++. interface header files can be used from server package or type library header can be generated from the component. We have used a COM server called MATHLIBLib and ICalculate is a basic calculator interface. Below is the interface detail for better understanding our client code.

interface ICalculate : IDispatch
{
  [propget, id(1), helpstring("Operand1 of calc")] HRESULT Operand1([out, retval] long *pVal);
  [propput, id(1), helpstring("Operand1 of calc")] HRESULT Operand1([in] long newVal);
  [propget, id(2), helpstring("Operand2 of calc")] HRESULT Operand2([out, retval] long *pVal);
  [propput, id(2), helpstring("Operand2 of calc")] HRESULT Operand2([in] long newVal);
  [id(3), helpstring("main operation method")] HRESULT DoOperation([in] char operation);
  [propget, id(4), helpstring("Result of calc")] HRESULT Result([out, retval] long *pVal);
}

COM Client with C++ header

This approach is simple a often known as raw approach. We need C++ header file of the COM server. This header file provides the C++ function prototypes of the com server components. We have below example written with raw functions.

  1. Collect the header (.h) file from COM server distribution and place in the same folder.
  2. Include this header file in C++ source and include client wrapper library in the project(optional).
  3. Call CoInitialize or CoInitializeEx to initialize the COM library on the current thread and identifies the concurrency.
  4. Provide Class ID and Interface ID and Call CoCreateInstance and obtain Interface pointer or Call CoGetClassObject and obtain more than one interfaces and call CreateInstance individually.
  5. Now call the interface methods. Example here we are calling a function put_OperandX() for setting the two operands of the calculator and DoOperation() to do the calculation. Later we are calling get_Result() for get the result.
  6. Release the pointer with Release() call.
  7. Call CoUninitialize at the end of all task.

COM Client with C++ demo

Note: We are not using any wrapper library in this example. All calls are to raw interfaces.

/* ComClientRaw.cpp : Defines the entry point for the console application. */
#include "MathLib.h"
#include "MathLib_i.c"
#include <objbase.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
10  {
11    long lOperand1, lOperand2, lResult;
12    unsigned char cOperation;
13    ICalculate * MyCalculator;
14    HRESULT hr;
15    
16    CoInitialize(NULL);
17 
18    hr = CoCreateInstance(CLSID_Calculate,
19                          NULL,CLSCTX_INPROC_SERVER,IID_ICalculate,(void**)&MyCalculator);
20    if(hr != 0){
21      cout << "CoCreateInstance failed error code %d" << hr;
22      CoUninitialize();
23      return hr;
24    }
25    cout << "MathLib.Calculate demo using raw C++ interface" << endl;
26    do {
27      cout << "Operand 1 : ";
28      cin >> lOperand1;
29      MyCalculator->put_Operand1(lOperand1);
30      
31      cout << "Operand 2 : ";
32      cin >> lOperand2;
33      MyCalculator->put_Operand2(lOperand2);
34 
35      cout << "Operation : ";
36      cin >> cOperation;
37      
38      MyCalculator->DoOperation(cOperation);
39      
40      MyCalculator->get_Operand1(&lOperand1);
41      MyCalculator->get_Operand2(&lOperand2);
42      MyCalculator->get_Result(&lResult);  
43      cout << lOperand1 << " " << cOperation << " " << lOperand2 << " = " << lResult << endl;
44 
45      cout << "Do you want to perform more calculation (y/n) ? ";
46      cin >> cOperation;
47 
48    } while(cOperation == 'y');
49 
50    MyCalculator->Release();
51    CoUninitialize();
52    return 0;
53  }

COM Client with C++ demo output

MathLib.Calculate demo using raw C++ interface
Operand 1 : 1
Operand 2 : 2
Operation : +
1 + 2 = 3
Do you want to perform more calculation (y/n) ? y
Operand 1 : 2
Operand 2 : 3
Operation : -
2 - 3 = -1
Do you want to perform more calculation (y/n) ? y
Operand 1 : 3
Operand 2 : 4
Operation : *
3 * 4 = 12
Do you want to perform more calculation (y/n) ? y
Operand 1 : 4
Operand 2 : 2
Operation : /
4 / 2 = 2
Do you want to perform more calculation (y/n) ? n
Press any key to continue

COM server vendors often provide client wrapping library. Client raw interface functions are wrapped inside this client side library. This library is optional but needed to make client code modular and it also adds the capability of managed error handling. Client calls these library calls and handles errors if needed. This makes easy to write the flow. Read more about client wrapper.

COM Client with type library/smart pointers

COM server can be written with type library support. Type library is a TLB extension file which is auto generated during compilation of com server. However a COM DLL or EXE can also contain a type library inside it. Visual C++ compiler can generated client wrapping library from type library(.tlb file) or directly from DLL/OCX/EXE component.

These wrapping library has an extension .tlh which means type library header and .tli which means type library implementation. Type library header file can be included in C++ and <Interface Name>Ptr classes can be used. These classes are called smart pointers class.

Smart pointer classes can handle errors and this makes CreateInterface and other functions more robust and manageable. Smart pointer classes are widely used nowadays and it replaces the use of client wrapper libraries. Below example code is written with the help of smart pointers. Logic and interface is same as previous example.

  1. #import COM DLL/EXE or the type library (.tlb) file and compile
  2. Compiler will generate type library header .tlh file and include it in C++ source.
  3. Call CoInitialize or CoInitializeEx to Initializes the COM library on the current thread and identifies the concurrency
  4. Provide Class ID and Interface ID and Call CoCreateInstance and obtain Interface pointer.or Call CoGetClassObject and obtain more than one interfaces and call CreateInstance individually.
  5. Now call the interface methods. Example here we are calling a function PutOperandX() for setting the two operands of the calculator and DoOperation() to do the calculation. Later we are calling GetResult() for get the result.
  6. Release call is not needed. Smart pointer object auto released when it is out of scope.
  7. CoUninitializeat the end after releasing all objects.

COM Client with type library demo

/* ComClientTlh.cpp : Defines the entry point for the console application. */
#include <windows.h>
#include <stdio.h>
#ifdef IMPORT_TLH
#import "MathLib.tlh"
#else
#import "MathLib.dll"  /* Default compile with import */
#else
10  #include <objbase.h>
11  #include <iostream>
12  using namespace std;
13 
14  int main(int argc, char* argv[])
15  {
16    long lOperand1, lOperand2;
17    unsigned char cOperation;
18 
19    CoInitialize(NULL);
20    MATHLIBLib::ICalculatePtr MyCalculator;
21 
22    if(MyCalculator.CreateInstance("MathLib.Calculate") != 0) {
23      cout << "MyCalculator.CreateInstance failed.";
24      CoUninitialize();
25      return -1;
26    }
27    cout << "MathLib.Calculate demo using smart pointer" << endl;
28    do {
29      cout << "Operand 1 : ";
30      cin >> lOperand1;
31      MyCalculator->PutOperand1(lOperand1);
32 
33      cout << "Operand 2 : ";
34      cin >> lOperand2;
35      MyCalculator->PutOperand2(lOperand2);
36 
37      cout << "Operation : ";
38      cin >> cOperation;
39      MyCalculator->DoOperation(cOperation);
40 
41      cout << MyCalculator->GetOperand1() << " " << cOperation 
42            << " " << MyCalculator->GetOperand2() << " = "
43            << MyCalculator->GetResult() << endl;
44 
45      cout << "Do you want to perform more calculation (y/n) ? ";
46      cin >> cOperation;
47 
48    } while(cOperation == 'y');
49 
50    MyCalculator.Release();
51    CoUninitialize();
52    return 0;
53  }

COM Client with type library demo output

MathLib.Calculate demo using smart pointer
Operand 1 : 1
Operand 2 : 2
Operation : +
1 + 2 = 3
Do you want to perform more calculation (y/n) ? y
Operand 1 : 2
Operand 2 : 3
Operation : -
2 - 3 = -1
Do you want to perform more calculation (y/n) ? y
Operand 1 : 2
Operand 2 : 3
Operation : *
2 * 3 = 6
Do you want to perform more calculation (y/n) ? y
Operand 1 : 4
Operand 2 : 2
Operation : /
4 / 2 = 2
Do you want to perform more calculation (y/n) ? n
Press any key to continue

You have viewed 1 page out of 66. Your COM/DCOM learning is 0.00% complete. Login to check your learning progress.

 Vote 1

Similar topics related to this section

# COM DCOM Interview Questions and Answers :: ALL Interview .com
# COM DCOM - COM DCOM Interview Questions
# COM interview questions | TechInterviews
# COM Interview Questions - CodeProject
# Com Dcom Interview Questions - Com and Dcom in Asp Net
# ATL Interview Questions and Answers :: ALL Interview .com
# ActiveX Interview Questions and Answers :: ALL Interview .com

* #1 webmaster Tue 29 Apr/2014 22:24:34(GMT)  Like 0 Unlike 0

Dear Users,

We are pleased to inform you that a forum/blog has been incorporated with www.mybestnotes.co.in. You are welcomed to add your comments, requests, codes, solutions and feedback to it. Please login(if already a member) or signup(for free) to avail to this facility.

Regards,
Webmaster

Your message goes here:

Name:Guest
Email:anonymous@unknown.com
My Post:*
Secutiry Code: ******  *
Preview this compose before posting this in discussion forum.
 
Note:
  1. Use [Sxx] code to show smiles. Example [S02]
  2. Use [URL ], example [URL http://www.google.com/]
  3. To display code or un formatted text use [CODE] [/CODE]. Example: [CODE] printf("Hello world"); [/CODE]
 [S01]   [S02]   [S03]   [S04]   [S05]   [S06]   [S07]   [S08] 
 [S09]   [S10]   [S11]   [S12]   [S13]   [S14]   [S15]   [S16] 
 [S17]   [S18]   [S19]   [S20]   [S21]   [S22]   [S23]   [S24] 

Note: Only members are allowed, * fields are mandatory.