Search code examples
visual-c++comvariant

Problem with SafeArray access using CComVariant


I have following block of code

 /////////////////////////////////////
 CComVariant newVal;

 //pass the CComVariant and get the strings array!!!
 GetStrList(newVal);
 USES_CONVERSION;

 if (((newVal.vt & VT_ARRAY) == VT_ARRAY) && ((newVal.vt & VT_BSTR) == VT_BSTR))
 {
SAFEARRAY* paArray = newVal.parray;
BSTR * str = NULL;
SafeArrayAccessData(paArray, (void**)&str);

SafeArrayUnaccessData(paArray);

long lLBound = 0;
long lUBound = 0;
long nCount = 0;

if (FAILED(SafeArrayGetLBound(paArray, 1, &lLBound)) ||
    FAILED(SafeArrayGetUBound(paArray, 1, &lUBound)))
{
    ASSERT(false);
    return FALSE;
}


nCount = ( lUBound - lLBound + 1 );
for (int i = 0 ; i < nCount ; i++)
{           
    m_cstrList.AddString(W2T(str[i]));                  
}   
//SafeArrayDestroy(paArray); ---> is it required here???

 }

 /////////////////////////////////////

method returing the safe arrays

 HRESULT GetStrList(VARIANT *pVal)
 {
USES_CONVERSION;

if (!pVal)
    return E_FAIL;

SAFEARRAYBOUND bound[1]; //single dimension array
bound[0].lLbound = 0;
bound[0].cElements = 10;

SAFEARRAY * A = SafeArrayCreate(VT_BSTR, 1, bound);

BSTR * str = NULL;
SafeArrayAccessData(A, (void**)&str);

//user wants the NT view OPC drivers list.
for (int i=0;i<10;i++)
{       
    str[i] = SysAllocString(T2W(mystrings[i]));     
}


VariantInit(pVal);
pVal->vt        = VT_ARRAY | VT_BSTR;
pVal->parray    = A;

SafeArrayUnaccessData(A);
A = NULL;

return S_OK;
 }

My doubt is, above first block of code has any memory leaks? Does the CComVariant itself handle every thing about the cleaning? or do i also manually do SafeArrayDestroy(paArray);

Thanks in Advance!


Solution

  • CComVariant destructor calls VariantClear() which frees whatever the variant was incapsulating, arrays included.

    One caveat: the array should not be locked at the time when VariantClear() is called. This means that if an exception is thrown after SafeArrayAccessData() but before SafeArrayUnaccessData() the latter will not be called and VariantClear() will not free resources.

    Therefore you better write a bracket class for pairing SafeArrayAccessData() and SafeArrayUnaccessData() calls.