I need to pass data from a C++ dll to a C# environment. Therefore I use a 2d SafeArray of doubles.
This function passes the data from C++ to C#:
void GetIndividualExposures(SAFEARRAY*& data)
{
SAFEARRAYBOUND bounds[2];
bounds[0].lLbound = 0;
bounds[0].cElements = 10;
bounds[1].lLbound = 0;
bounds[1].cElements = 20;
long l_dimensions[2];
int index = 0;
data = SafeArrayCreate(VT_R8, 2, bounds);
double **pVals;
HRESULT hr = SafeArrayAccessData(data, (void**)&pVals);
if (SUCCEEDED(hr))
{
for (ULONG i = 0; i < bounds[0].cElements; i++)
{
for (ULONG j = 0; j < bounds[1].cElements; j++)
{
l_dimensions[0] = i;
l_dimensions[1] = j;
SafeArrayPutElement(data, l_dimensions, &data_source[i][j]);
}
}
SafeArrayUnaccessData(data);
}
}
This works, fine, all data is available as needed in my C# environment. However I get a memory leak. I tried to use a second C++ function to free the memory:
void DeallocateExternal(SAFEARRAY*& data)
{
SafeArrayDestroy(data);
data = NULL;
}
but it has no effect. What did I do wrong? Is there any possibility to free the memory of the SafeArray after use in C#? Or how can I do this?