How to iterate through SAFEARRAY **

六眼飞鱼酱① 提交于 2019-12-01 03:16:21

Safearrays are created with SafeArrayCreate or SafeArrayCreateVector, but as you ask about iterating over a SAFEARRAY, let's say you already have a SAFEARRAY returned by some other function. One way is to use SafeArrayGetElement API which is especially convenient if you have multidimensional SAFEARRAYs, as it allows, IMO, a bit easier specifying of the indices.

However, for vectors (unidimensional SAFEARRAY) it is faster to access data directly and iterate over the values. Here's an example:

Let's say it's a SAFEARRAY of longs, ie. VT_I4

// get them from somewhere. (I will assume that this is done 
// in a way that you are now responsible to free the memory)
SAFEARRAY* saValues = ... 
LONG* pVals;
HRESULT hr = SafeArrayAccessData(saValues, (void**)&pVals); // direct access to SA memory
if (SUCCEEDED(hr))
{
  long lowerBound, upperBound;  // get array bounds
  SafeArrayGetLBound(saValues, 1 , &lowerBound);
  SafeArrayGetUBound(saValues, 1, &upperBound);

  long cnt_elements = upperBound - lowerBound + 1; 
  for (int i = 0; i < cnt_elements; ++i)  // iterate through returned values
  {                              
    LONG lVal = pVals[i];   
    std::cout << "element " << i << ": value = " << lVal << std::endl;
  }       
  SafeArrayUnaccessData(saValues);
}
SafeArrayDestroy(saValues);
Roman R.

MSDN SafeArrayGetElement function gives you a code snippet on using SafeArrayGetElement to obtain individual object to array.

SAFEARRAY structure and SafeArray* functions explain the available API.

In ATL/MFC project you would want to use wrapper classes e.g. CComSafeArray to make things simpler and easier. See Simplifying SAFEARRAY programming with CComSafeArray on this.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!