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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With