Safearrays 是用SafeArrayCreate
or创建的SafeArrayCreateVector
,但是当您询问迭代 SAFEARRAY 时,假设您已经有一个由其他函数返回的 SAFEARRAY。一种方法是使用SafeArrayGetElement
API,如果您有多维 SAFEARRAY,这将特别方便,因为它允许 IMO 更容易指定索引。
但是,对于向量(一维 SAFEARRAY),直接访问数据并迭代值会更快。这是一个例子:
假设它是long
s 的 SAFEARRAY,即。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);