18.04.2015 Views

ArcGIS Engine Developer Guide

ArcGIS Engine Developer Guide

ArcGIS Engine Developer Guide

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

VISUAL C++<br />

extern "C" const GUID __declspec(selectany) CLSID_Foo = \<br />

{0x2f3b470c,0xb01f,0x11d3,{0x83,0x8e,0x00,0x00,0x00,0x00,0x00,0x00}};<br />

// Declare Smart Pointers for IFoo, IBar, and IGak interfaces.<br />

_COM_SMARTPTR_TYPEDEF(IFoo, __uuidof(IFoo));<br />

_COM_SMARTPTR_TYPEDEF(IBar, __uuidof(IBar));<br />

_COM_SMARTPTR_TYPEDEF(IGak, __uuidof(IGak));<br />

STDMETHODIMP SomeClass::Do()<br />

{<br />

// Create Instance of Foo class and QueryInterface (QI) for IFoo interface.<br />

IFooPtr ipFoo;<br />

HRESULT hr = ipFoo.CreateInstance(CLSID_Foo);<br />

if (FAILED(hr)) return hr;<br />

// Call method on IFoo to get IBar.<br />

IBarPtr ipBar;<br />

hr = ipFoo->get_Bar(&ipBar);<br />

if (FAILED(hr)) return hr;<br />

// QI IBar interface for IGak interface.<br />

IGakPtr ipGak(ipBar);<br />

// Call method on IGak.<br />

hr = ipGak->DoSomething();<br />

if (FAILED(hr)) return hr;<br />

// Explicitly call Release().<br />

ipGak = 0;<br />

ipBar = 0;<br />

// Let destructor call IFoo’s Release.<br />

return S_OK;<br />

}<br />

One of the main advantages of using the DTC smart pointers is that they are<br />

automatically generated from the #import compiler statement for all interface<br />

and coclass definitions in a type library. For more details on this functionality, see<br />

the later section ‘Importing <strong>ArcGIS</strong> type libraries’.<br />

It is possible to create an object implicitly in a DTC smart pointer’s constructor,<br />

for example:<br />

IFooPtr ipFoo(CLSID_Foo)<br />

However, this will raise a C++ exception if there is an error during object creation—for<br />

example, if the DLL containing the object implementation was<br />

accidentally deleted. This exception will typically be unhandled and cause a crash.<br />

A more robust approach is to avoid exceptions in COM, call CreateInstance<br />

explicitly, and handle the failure code, for example:<br />

Chapter 4 • <strong>Developer</strong> environments • 111

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!