如何迭代 SAFEARRAY **

2023-11-23

如何通过 C++ safearray 指针迭代到指针并访问其元素。

我尝试复制 Lim Bio 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);

代替

HRESULT __stdcall GetTestStructArray([out] SAFEARRAY(TestStruct)* test_struct_array);

有任何想法吗?

提前致谢


Safearrays 是用以下命令创建的SafeArrayCreate or SafeArrayCreateVector,但是当您询问如何迭代 SAFEARRAY 时,假设您已经有一个由其他函数返回的 SAFEARRAY 。一种方法是使用SafeArrayGetElement如果您有多维 SAFEARRAY,API 会特别方便,因为在我看来,它允许更轻松地指定索引。

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

假设它是一个 SAFEARRAYlongs,即。 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何迭代 SAFEARRAY ** 的相关文章

随机推荐