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