如何遍历 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);
相关文章