如何迭代SAFEARRAY**

Tru*_*der 10 c++ com safearray

如何迭代C++ safearray指针指向并访问其元素.

我试图复制发表林生物LIONG解决 http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/022dba14-9abf-4872-9f43-f4fc05bd2602 但奇怪的是,该IDL方法签名出来了

HRESULT __stdcall GetTestStructArray([out] SAFEARRAY ** test_struct_array);
Run Code Online (Sandbox Code Playgroud)

代替

HRESULT __stdcall GetTestStructArray([out] SAFEARRAY(TestStruct)* test_struct_array);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

提前致谢

Zde*_*vic 21

Safearrays是用SafeArrayCreateor 创建的SafeArrayCreateVector,但是当您询问迭代SAFEARRAY时,假设您已经有一些其他函数返回的SAFEARRAY.一种方法是使用SafeArrayGetElementAPI,如果你有多维SAFEARRAYs,这是特别方便的,因为它允许IMO更容易指定索引.

但是,对于向量(单维SAFEARRAY),直接访问数据并迭代值更快.这是一个例子:

让我们说它是s的SAFEARRAY long,即.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);
Run Code Online (Sandbox Code Playgroud)

  • SafeArrayDestroy()不属于此代码.如果您不拥有阵列,请不要销毁阵列. (5认同)