Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an element from SAFEARRAY (or convert it into a long array)

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?

like image 988
merch Avatar asked Feb 14 '23 13:02

merch


2 Answers

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...

like image 173
Len Holgate Avatar answered Apr 28 '23 20:04

Len Holgate


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.

like image 42
Igor Tandetnik Avatar answered Apr 28 '23 20:04

Igor Tandetnik