Calling COM Objects – Technique 4 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. 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 previous blog entries I have shown you how to call the Sum method of the MyFuncs class using classic C++ native code, and from JavaScript and VBScript scripts. In this blog entry, I will show you how to call the COM object using C# managed code. Launch a new instance of Visual Studio 2005. Do a File | New | Project. Choose the Visual C# Project Type, and select the Console Application template. Save at any convenient location (say, C:\VS223) with any convenient name (say, CSharpDriver) and click OK. In the Solution Explorer window, right click on your project, and select Add Reference. In the Add Reference dialog box, select the Browse tab, then navigate to the MyMathLib dll file and click OK. Basically you have told Visual Studio you want to use the DLL file. Now modify the VS-generated code to get this:
using System;
namespace CSharpDriver
  class Program
    static void Main(string[] args)
      Console.WriteLine("\nBegin COM test\n");
      MyMathLibLib.MyFuncsClass mf = new MyMathLibLib.MyFuncsClass();
      int val1 = 5;
      int val2 = 4;
      int answer = mf.Sum(val1, val2);
      Console.WriteLine("Five plus four is " + answer);
      Console.WriteLine("\nEnd test");
    } // Main()
  } // class Program
} // ns
Compared to calling COM using native C++, the .NET environment greatly simplifies using classic COM. The key line of code is:
MyMathLibLib.MyFuncsClass mf = new MyMathLibLib.MyFuncsClass();
Notice that Visual Studio calls my namespace MyMathLibLib (appending a "Lib"), and that .NET identifies the MyFuncs coclass as MyFuncsClass (appending a "Class"). Here I instantiate an object named mf, which is type MyFuncClass, and which is a friendly face to my actual underlying COM interface/component/class. I could also have declared mf as an Interface (MyFuncs). Once instantiated, I can call the Sum() method just as I would a non-COM method.
This entry was posted in Software Test Automation. Bookmark the permalink.