Home Search Contact us About us
Title COM with smart pointers (Used across several functions)
Summary Use this method to instantiate a COM object without having to call CoCreateInstance. It also allows the COM object to be declared in the class declaration and created in InitialDialog() or simular, then used throughout the class.
Contributor John McTainsh
Published 10-Sep-2000
Last updated 2-Aug-2001
Page rating   90% for 2 votes Useless Brilliant


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


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 start-up 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.     

In the header of the class place the object reference variable. UseItHere.h

    ICtrlFlashPtr m_pFlash;                 //Smart pointer

In class contructor initialise the variable. UseItHere.cpp Constructor.

    m_pFlash = NULL;

In class destructor release the object. UseItHere.cpp Destructor.

    m_pFlash = NULL;

In an initialisation routine such as InitDialog instantiate the object. UseItHere.cpp

    //Instantiate the smart pointer
    hr = m_pFlash.CreateInstance( __uuidof( CtrlFlash ) );

    if( FAILED( hr ) )
        TRACE( _T("ERROR : Instanciate FLASH FAILED %x!!!\n"), hr );
        AfxMessageBox( "Flash load failed\n");
        return FALSE;

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

        TRACE( _T("Inital count = %d\n"), pFlash->nBeerCount );
    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