How to iterate through SAFEARRAY **(如何遍历 SAFEARRAY **)
问题描述
如何遍历 C++ 安全数组指针并访问其元素.
how to iterate through C++ safearray pointer to pointer and access its elements.
我尝试复制 Lim Bio Liong 发布的解决方案http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/022dba14-9abf-4872-9f43-f4fc05bd2602但最奇怪的是 IDL 方法签名竟然是
I tried to replicate the solution posted by Lim Bio Liong http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/022dba14-9abf-4872-9f43-f4fc05bd2602 but the strangest thing is that the IDL method signature comes out to be
HRESULT __stdcall GetTestStructArray([out] SAFEARRAY ** test_struct_array);
而不是
HRESULT __stdcall GetTestStructArray([out] SAFEARRAY(TestStruct)* test_struct_array);
有什么想法吗?
提前致谢
推荐答案
Safearrays 是使用 SafeArrayCreate
或 SafeArrayCreateVector
创建的,但是当您询问迭代 SAFEARRAY 时,让我们假设您已经有其他函数返回的 SAFEARRAY .一种方法是使用 SafeArrayGetElement
API,如果您有多维 SAFEARRAY,这会特别方便,因为它允许 IMO 更轻松地指定索引.
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.
但是,对于向量(一维 SAFEARRAY),直接访问数据并迭代值会更快.这是一个例子:
However, for vectors (unidimensional SAFEARRAY) it is faster to access data directly and iterate over the values. Here's an example:
假设它是 long
的 SAFEARRAY,即.VT_I4
Let's say it's a SAFEARRAY of long
s, 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);
这篇关于如何遍历 SAFEARRAY **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何遍历 SAFEARRAY **


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01