Assuming your array contains ints (use SafeArrayGetVartype
to verify), is 1-dimensional (use SafeArrayGetDim
) and 0-based (use SafeArrayGetLBound
), the correct way to access it is this:
int value;
LONG indices[] = { 0 };
if (FAILED(SafeArrayGetElement(pArray, indices, &value))) {
// getting element failed - probably bad index
}
// value now contains the correct value
You can use SafeArrayAccessData
too, but unless you have identified a performance problem, it's better not to.
In general when dealing with OLE structures (VARIANT
, SAFEARRAY
, etc.) you should always use the provided utility functions. They are part of Windows, not MFC. Here's the reference for arrays:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms221145(v=vs.85).aspx
However, if you can, I strongly recommend you use ATL's wrapper for SAFEARRAY, CComSafeArray. See the documentation and a short blog article showing its usage:
http://msdn.microsoft.com/en-us/library/3xzbsee8.aspx http://msmvps.com/blogs/gdicanio/archive/2011/02/04/simplifying-safearray-programming-with-ccomsafearray.aspx