Search code examples
c++safearray

Can't store/retrieve the value from the SafeArray


I am new to the SAFE ARRAY concept MSDN didn't help much. I tried to pass an safe array to a function.

Here is my code

void func2(__int64 *a)
{
    *a = 100000;
}
void func1(SAFEARRAY **saOfmem )\
{
    LONG  rgIndex = 0;
    __int64 memVal;
    func2(&memVal);
    SafeArrayPutElement(*saOfmem,&rgIndex,&memVal);

}

int _tmain(int argc, _TCHAR* argv[])
{
    SAFEARRAY *saOfmem;
    SAFEARRAYBOUND rgsabound[1];
    __int64 val;

    rgsabound[0].lLbound = 0;
    rgsabound[0].cElements = 1;
    saOfmem = SafeArrayCreate(VT_UI8 | VT_BYREF, 1, rgsabound);

    func1(&saOfmem);

    SafeArrayGetElement(saOfmem,0,&val);
    return 0;
}

Unfortunately the value is not updated in the safe array. What I am doing wrong?


Solution

    1. You should not use VT_BYREF, it means that pass values by reference. And you have a simple array of int64, no references.

    2. You should use non-null index (see comments). SafeArrayGetElement expects a POINTER to index array, not an integer as a second argument.

      rgsabound[0].lLbound = 0;
      rgsabound[0].cElements = 1;
      saOfmem = SafeArrayCreate(VT_UI8, 1, rgsabound); ///<< remove VT_BYREF
      
      func1(&saOfmem);
      
      LONG rgIndex = 0; // <<< use non-null as parameter
      SafeArrayGetElement(saOfmem, &rgIndex, &val);