Home Search Contact us About us
Title COM with smart pointers (Within single function)
Summary Use this method to instanciate a COM object without having to call CoCreateInstance. This is suitable only if the object is created and destroyed withing the same function.
Contributor John McTainsh
Published 9-Sep-2000
Last updated 2-Aug-2001
Page rating   82% for 15 votes Useless Brilliant

Description.

Smart pointers are a relatively simple method of accessing COM objects. They encapsulate much of the tricky code required to instantiate and use a COM object.

Where do the names come from?

The name of the items in this example can be found in the tlh file and class factory as follows;

Name here Purpose How to find
TrickyCom.exe Name of the file containing the object. May be a DLL or EXE. Path and name of file.
TRICKYCOMLib This is the Library name space The namespace is located in .tlh and begins with namespace and ends with ...Lib {
ICtrlFlasherPtr Smart pointer name Look in .tlh and add Ptr to the end of the first parameter in _COM_SMARTPTR_TYPEDEF(ICtrlFlasher,
CtrlFlasher The coclass name Look in .tlh and use the name defines in struct /* coclass */ CtrlFlasher;
Increment() and Count The methods and properties Look in .tlh for the // Property data and // Wrapper methods for error-handling sections

Solution.

In StdAfx.h add.

//Reference Com object to create *.tlh and *.tli
#import "C:\Temp\TrickyCom\Debug\TrickyCom.exe"
//The namespace is located in *.tlh and ends in ...Lib {
using namespace TRICKYCOMLib;

In Gizzmo.cpp in BOOL CGizzmoApp::InitInstance(); or any simular startup function that is called only once.

    //Initialise the application for use with COM objects
    HRESULT hr = CoInitialize( NULL );
    if( FAILED( hr ) )
    {
        AfxMessageBox( "CoInitialize failed\n");
        return FALSE;
    }

    //TODO Call CoUninitialize(); in the Destructor or other location
    //when all COM activity is completed.

Place this code where you want to access the object. ie In a button handler.

    //
    //Load Com object and use it
    //
    try
    {
        //Create the Common Object Model.
        ICtrlFlasherPtr pFlash( __uuidof(CtrlFlasher) );

        //Use the smart pointer
        TRACE( _T("Inital count = %d\n"), pFlash->Count );
        pFlash->Increment();
    }
    catch( _com_error e )
    {
        //Catch and display errors
        TRACE( _T("Com Error %x, %s\n"), e.Error, e.ErrorMessage() );
    }       
Comments Date
Home Search Contact us About us