Calling COM Objects – Techniques 2 and 3 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 my last blog entry I showed how to called the classic COM object using native Win32 C++ code — and it was ugly — very ugly. In this entry I’ll demonstrate calling the COM object using JavaScript and VBScript. To use JavaScript, simply launch an instance of notepad and type this code:

// test.js
WScript.Echo("Begin COM test\n");
var o = new ActiveXObject("MyFuncsLib.MyMath");
var arg1 = 4;
var arg2 = 8;
var ans = o.Sum(arg1,arg2);
WScript.Echo("Four plus eight gives ", ans);
// end script

Save as file test.js and then execute from a command shell by typing:

C:\VS223\YourName> cscript test.js

Much easier than using C++. This is one of the key points of COM objects: they can be called by many different languages. Here we use the JavaScript ActiveXObject() method to instantiate the COM object using its ProgID. Using VBScript is very similar. Launch an instance of notepad and type this code:

‘file: test.vbs
WScript.Echo "Start"
Dim myObj
Set myObj = CreateObject("MyMathLib.MyFuncs")
x = 3
y = 9
ans = myObj.Sum(x,y)
WScript.Echo "Three plus nine is " & ans
WScript.Echo "End"
‘end script

Save as file test.vbs and then execute from a command line by typing:

C:\VS223\YourName> cscript test.vbs

The main difference, apart from syntax, is that VBScript uses the CreateObject() method.

This entry was posted in Software Test Automation. Bookmark the permalink.