How to create and initialize SAFEARRAY of doubles in C++ to pass to C#

Chris picture Chris · Sep 16, 2010 · Viewed 31.8k times · Source

My C# method needs to be invoked from C++

Originally my C# method takes a parameter of type double[], but when calling from C++ it becomes a SAFEARRAY

In C++ I need to take data from an array of doubles, and populate a SAFEARRAY. I have not found any sample code to do this.

Any help is appreciated

Answer

Liton picture Liton · Sep 17, 2010

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);
    }
}

Free the pointer when you are finished like 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

If you use ATL for C++, then better use CComSafeArray declared in "atlsafe.h". This is wrapper for SAFEARRAY. link text