安全陣列是用SafeArrayCreate
或SafeArrayCreateVector
創建的,但是當您詢問關於SAFEARRAY的迭代時,假設您已經有一個SAFEARRAY由其他函數返回。一種方法是使用SafeArrayGetElement
API,如果您擁有多維SAFEARRAY,則API特別方便,因爲它允許IMO更容易地指定索引。
但是,對於矢量(單維SAFEARRAY),直接訪問數據並迭代這些值會更快。下面是一個例子:
假設這是一個SAFEARRAY long
s,即。 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);
什麼是'cmd'? ! – 2012-09-18 20:09:02