문제

I'm trying to get the elements from a SAFEARRAY (returned as output of a function) in Visual C++.

I've never ever used a SAFEARRAY before, so I don't know how to deal with it. Should I convert the SAFEARRAY into a long array (how?) or can I simply use the index of the values inside the SAFEARRAY?

도움이 되었습니까?

해결책

You should probably familiarise yourself with the SafeArray documentation on MSDN.

What you probably want to do is call SafeArrayAccessData() to obtain a pointer to the safe array's memory buffer and then iterate the values directly. This is likely the most efficient way to access the values. The code below assumes a lot, you should make sure that you understand these assumptions (by reading the safe array docs) and that they hold for your particular situation...

void Func(SAFEARRAY *pData)
{
   void *pVoid = 0;

   HRESULT hr = ::SafeArrayAccessData(pData, &pVoid);

   MyErrorCheck::ThrowOnFailure(hr);

   const long *pLongs = reinterpret_cast<long *>(pVoid);

   for (int i = 0; i < pData->rgsabound[0].cElements; ++i)
   {
      const long val = pLongs[i];

      DoThingWithLong(val);          
   }

   hr = ::SafeArrayUnaccessData(pData);

   MyErrorCheck::ThrowOnFailure(hr);
}

Note that the code above hasn't seen a compiler...

다른 팁

See SafeArrayGetElement or SafeArrayAccessData. The former retrieves elements one by one. The latter gives you a pointer to a flat C-style array that this SAFEARRAY instance wraps (don't forget to SafeArrayUnaccesData when you are done).

Note also that, most likely, you are responsible for destroying the array (with SafeArrayDestroy) once you no longer need it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top