#include <atlcomcli.h>
#include <atlsafe.h>
void SafeArrayTest()
{
    SAFEARRAY * psa; // The safearray
    SAFEARRAYBOUND rgsabound[1]; // A one dimensional array
    long * pData;
    long lValue, lIndex;
    rgsabound[0].lLbound = 0; // With lower bound 0;
    rgsabound[0].cElements = 10; // With 10 elements;
    psa = SafeArrayCreate(VT_I4, 1, rgsabound); // Create an array of integers
    SafeArrayAccessData(psa,(void**)&pData); // Get a pointer to the data
    for (int i=0;i<10;++i)
        pData[i] = i;  // Fill array with values from 0 to 9
    SafeArrayUnaccessData(psa); // pData is now invalid.
    lIndex = 5;
    SafeArrayGetElement(psa,&lIndex,(void*)&lValue); // lValue is now 5
    ++lValue;        // lValue is now 6
    SafeArrayPutElement(psa,&lIndex,(void*)&lValue); // psa[5] is now 6   
    CComSafeArray<long> comSafeArray;
    comSafeArray.Attach(psa);
    // NOTICE: Don't use like this:
    // CComSafeArray<long> comSafeArray(psa); // or
    // comSafeArray = psa; // Because they will call CopyFrom to copy the whole safe array
    // Do some operation on comSafeArray...
    comSafeArray[5] = 7;
    comSafeArray.Detach();
    SafeArrayDestroy(psa); // Destroy the SAFEARRAY and free memory
}