OOPortal OOPortal


Operator Overloading  «Prev  Next»

Safe Array in C++

Here is the implementation of a safe array that was used in Building Classes in C++:
//Implementation of a safe array type vect
class vect {
public:
   explicit vect(int n = 10);
   ~vect() { delete []p; }
   int& element(int i);        //access p[i]
   int  ub() const
     { return (size - 1); }  //upper bound
private:
   int*  p;
   int   size;
};

vect::vect(int n) : size(n){
   assert(n > 0);
   p = new int[size];
   assert(p);
}

int& vect::element(int i){
   assert (i >= 0 && i < size);
   return p[i];
}

Following is the code to create a safearray in C++.
#include<oaidl.h>

void CreateSafeArray(SAFEARRAY* saData){
    double data[10]; // some sample data to write into the created safearray
    SAFEARRAYBOUND  Bound;
    Bound.lLbound   = 0;
    Bound.cElements = 10;

    *saData = SafeArrayCreate(VT_R8, 1, &Bound);

    double HUGEP *pdFreq;
    HRESULT hr = SafeArrayAccessData(*saData, (void HUGEP* FAR*)&pdFreq);
    if (SUCCEEDED(hr)) {
            // copy sample values from data[] to this safearray
        for (DWORD i = 0; i < 10; i++){
            *pdFreq++ = data[i];
        }
        SafeArrayUnaccessData(*saData);
    }
}

When you are finished free the pointer using the following code.
  SAFEARRAY* saData;
  CreateSafeArray(&saData); // Create the safe array
  // use the safearray
  ...
  ...

  // Call the SafeArrayDestroy to destroy the safearray 
  SafeArrayDestroy(saData);
  saData = NULL; // set the pointer to NULL