Advertising

Using COM objects from MFC

Contents

Introduction

Using fully visual ActiveX objects is usually quite simple. However, non-visual COM components can not just be dragged onto a form. This documents explains how to use COM objects in your projects, without access to the source code of the COM object, using the appropriate auto-generated wrappers.

Intializing

In order to to use COM in your MFC app, you will need to call AfxOleInit() in the InitInstance() of your application class.

Creating the Wrapper class

Open the Classwizard from the View menu. Click [Add Class]. Select 'From a type library...'.

Select the Type Library. This is usually a file with a '.tlb' extension supplied with the dll/exe/ocx, or it may be contained within the dll/exe/ocx file.

In the 'Confirm Classes' dialog box, select an interface, then edit the names of the files which will be auto-generated. I suggest you put '_Wrapper' at the end of both the class name and the file names.For instance: 'IExample_Wrapper', 'Example_Wrapper.h', 'Example_Wrapper.c'.

The new class will be added to the project and should show up in the ClassView tab of the Workspace. This class will be derived from COleDispatchDriver.

Instantiating the COM object

You must create an instance of the COM object by using the CreateDispatch() member of the wrapper class, passing it either a GUID or the text identifier. Note that you must refer to the 'package' name, the Interface, and the version number of the Interface.

e.g.

CExample_Wrapper exampleWrapper;
exampleWrapper.CreateDispatch(_T("Example.Example.1"));

Using the COM object's methods

The auto-generated wrapper will have methods for each of the COM methods.These methods do not return the HRESULT. Instead they will return the [out, return] parameter if any.

If a COM methods returns anything other than S_OK, a COleDispatchException will be thrown. You may detect this with a try/catch block.

e.g.

try
{
    int iTemp = exampleWrapper.GetValue();ࠠ
}
catch(COleDispatchException* pEx)
{
    //do something.
}

Copyright © Murray Cumming. Verbatim copying and distribution of this entire article is permitted in any medium, provided this notice is preserved.

Murray's Web Pages