4

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?

aNDo
  • 41
  • 1
  • 3

3 Answers3

1

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

Community
  • 1
  • 1
Motti
  • 110,860
  • 49
  • 189
  • 262
1

I don't see any such problem in your code. If you can share the code of ListSomething(..) method, then we might be able to find something but a similar code like this works perfectly with me.

void MyMethod(SAFEARRAY** pArray)
{
    int i = (*pArray)->cbElements;
    return;
}

CComSafeArray&lt;BSTR&gt; myArray;
myArray.Add(CComBSTR(_T("Test")));
myArray.Add(CComBSTR(_T("Best")));
myArray.Add(CComBSTR(_T("Rest")));
MyMethod(&(myArray.m_psa));
Marco A.
  • 43,032
  • 26
  • 132
  • 246
Aamir
  • 14,882
  • 6
  • 45
  • 69
-1

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
  • 11,510
  • 1
  • 38
  • 59
  • 1
    Your answer is almost correct, but the implicit conversion doesn't work with the reference operator on the `sa` argument. – sourcenouveau Feb 03 '12 at 17:52