18.04.2015 Views

ArcGIS Engine Developer Guide

ArcGIS Engine Developer Guide

ArcGIS Engine Developer Guide

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

C++ APPLICATION PROGRAMMING INTERFACE<br />

sure to call the Clear method before reusing the variable.<br />

ipFoo->put_Name(CComBSTR(L"NewName"));<br />

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

// Create a VT_I4 variant (signed long).<br />

CComVariant vValue(12);<br />

// Change its data type to a string.<br />

hr = vValue.ChangeType(VT_BSTR);<br />

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

Some method calls in IDL are marked as being optional and take a variant parameter.<br />

However, in C++ (and VC++) these parameters still have to be supplied. To<br />

signify that a parameter value is not supplied, a variant is passed specifying an<br />

error code or type DISP_E_PARAMNOTFOUND:<br />

CComBSTR documentFilename(L"World.mxd");<br />

CComVariant noPassword;<br />

noPassword.vt = VT_ERROR;<br />

noPassword.scode = DISP_E_PARAMNOTFOUND;<br />

HRESULT hr = ipMapControl->LoadMxFile(documentFilename, noPassword);<br />

However, if you do have a value that you want to pass in for the variant, use the<br />

smart type, CComVariant.<br />

int val = 1;<br />

CComVariant smartVal(val);<br />

ipRowBuffer->put_Value(2, smartVal);<br />

When working with CComBSTR and CComVariant, the Detach function releases<br />

the underlying data type from the smart type and can be used when passing a<br />

result as an [out] parameter of a method. The use of the Detach method with<br />

CComBSTR is shown below:<br />

HRESULT CFoo::get_Name(BSTR* name)<br />

{<br />

if (name==0) return E_POINTER;<br />

CComBSTR bsName(L"FooBar");<br />

*name = bsName.Detach();<br />

}<br />

A common practice with smart pointers is to use Detach to return an object from<br />

a method call. When returning an interface pointer the COM standard is to<br />

increment reference count of the [out] parameter inside the method implementation.<br />

It is the caller’s responsibility to call Release when the pointer is no longer<br />

required. Consequently, care must be taken to avoid calling Detach directly on a<br />

member variable. A typical pattern is shown below:<br />

HRESULT CFoo::get_Bar(IBar **pVal)<br />

{<br />

if (pVal==0) return E_POINTER;<br />

// Constructing a local smart pointer using another smart pointer<br />

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

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

Saved successfully!

Ooh no, something went wrong!