如何遍历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);有什么想法吗?
提前感谢
发布于 2012-09-19 04:12:23
SAFEARRAY是用SafeArrayCreate或SafeArrayCreateVector创建的,但是当您询问有关迭代SAFEARRAY的问题时,假设您已经有一个由其他函数返回的SAFEARRAY。一种方法是使用SAFEARRAYs,如果你有多维的SafeArrayGetElement,这会特别方便,因为它允许,更容易指定索引。
但是,对于向量(一维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);发布于 2012-09-19 04:05:25
MSDN SafeArrayGetElement function为您提供了使用SafeArrayGetElement获取要数组的单个对象的代码片段。
SAFEARRAY structure和SafeArray*函数解释了可用的接口。
在ATL/MFC项目中,你可能想要使用包装器类,比如CComSafeArray来让事情变得更简单和容易。关于这一点请参阅Simplifying SAFEARRAY programming with CComSafeArray。
https://stackoverflow.com/questions/12484109
复制相似问题