views:

52

answers:

1

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

+3  A: 

Following is the code to create a safearray in C++.

#include<oaidl.h>

void CreateSafeArray(SAFEARRAY* saData)        
{
    double data[10];
    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))
    {
        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);
  SafeArrayDestroy(saData);

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

Liton
Great code, well said.
Gravitas