tags:

views:

916

answers:

3

Hi guys,

This most likely has a very simple answer, but I can't figure it out.

I'm trying to refactor some code that looks like this:

SAFEARRAY* psa;
long* count;
HRESULT hr = pSomeInterface->ListSomething(&psa, &count);
if (SUCCEEDED(hr))
{
    CComSafeArray<BSTR> sa;
    if (*count > 0)
    {
        sa.Attach(psa);
    }
}

// perform operations on sa
// allow CComSafeArray to destroy the object

return hr;

I would like to change the code to something like:

CComSafeArray<BSTR> sa;
long* count;
hr = pSomeInterface->ListSomething(&(sa.m_psa), &count);

if (SUCCEEDED(hr))
{
    // perform operations on sa
}

But when I execute this, sa contains garbage. What's happening and why? What is the correct syntax?

+1  A: 
Aamir
A: 

You're defeating the whole point of using CComSafeArray by effectively bypassing it and accessing its internal SAFEARRAY directly. CComSafeArray has an explicit LPSAFEARRAY operator defined, so you should be able to do this instead:

CComSafeArray<BSTR> sa;
long* count;
HRESULT hr = pSomeInterface->ListSomething(&sa, &count);
if (SUCCEEDED(hr))
{    
    // perform operations on sa
}
Stu Mackellar
A: 

You should use CComSafeArray<T>::GetSafeArrayPtr(). However Aamir's way of using &(sa.m_psa) should work too.

Motti