Some examples of how to use the TSafeArrayT SAFEARRAY wrappers.

By: mykle hoban

Abstract: This article shows several ways to use the TSafeArrayT template to maniuplate COM SAFEARRAYs


How do I use the SAFEARRAY wrappers provided in C++Builder?


Below are several examples of how to use the SAFEARRAY wrappers. These are made with both client- and server-side in mind.

#include <safearry.h>

ITestServerDisp thesrv;  //sample server object.

//send an array to the server:
TSafeArrayDim1 dim(10); //create a 1-dimensional array with 10 elements
TSafeArrayBSTR1 bstr_array(dim); //of BSTRs
for (int i=0; i<10; i++) //fill it in
  bstr_array[i] = WideString("message " + i);

thesrv.SafeArrayPutMethod(bstr_array.Detach()); //send it to the server!

//receive a BSTR array from the server:

//NOTE: only call the below function if you never called Detach()
bstr_array.Destroy();  //clear our current array

thesrv.SafeArrayGetMethod(&bstr_array); //get it from the server!
//BoundsLength is a 0 based array of dimensions
//(BoundsLength[0] is the length of the array at the first dimension)
for (int i=0; i<bstr_array.BoundsLength[0]; i++)
//free our funky array (done automatically in destructor)

Server Response from: ETNASC03