Calling COM Objects – Technique 1 of 5

In a recent series of blog posts, I described how to write a custom COM object using C++ and the ATL wizard in Visual Studio 2005. (See Introduction to COM – Step 0 of 12).My COM component is named MyMathLib and contains a class ("coclass") named MyFuncs which in turn holds two methods — Sum(x,y) and Product(x,y) which just return the sum and product (result of multiplication) of two long ints. Let’s suppose that my COM component project is saved in a root directory arbitrarily named VS223. In this blog entry, I will show you how to call the COM object from a classic C++ program. Launch a new instance of Visual Studio 2005. Do a File | New | Project. Choose Win32 -> Win32 Console Application. Save at any convenient location (say, C:\VS223) with any convenient name (say, Test). Accept the default Application Settings. In the Test.cpp source, blast away the VS-generated code and replace with this:
#include "stdafx.h"
#include <stdio.h>
#include "..\MyMathLib\MyMathLib.h"
#include "..\MyMathLib\MyMathLib_i.c"
int main(int argc, char* argv[])
  IMyFuncs* ptr;
  long Answer;
  hr = ptr->Sum(5,4, &Answer);
  printf("\nFive plus four is %d \n", Answer);
  return 0;
Notice the #includes refer to the COM File name but inside the code you refer to the Class name. Build the project, then launch a command shell, navigate to the Test.exe file and execute. CoInitialize() initializes the COM library on the current thread of execution. The ptr variable is a pointer to the COM interface. The call to CoCreateInstance() does all the messy work of instantiating a COM object and associating the object with pointer ptr. We use the arrow notation to access the Sum() method. All in all, extremely ugly and you can see why Microsoft created .NET to eliminate having to use COM for simple applications programs.
This entry was posted in Software Test Automation. Bookmark the permalink.