I am calling a c++ dll from c#. I want to create a safearray (within a structure)in the c++ dll and pass it back to the c#.
The program crashes when returning to the c# with rhe following message:
An unhandled exception of type 'System.ExecutionEngineException' occurred in ConsoleApplication2.exe

the c# code is:
using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct retVar
{
public object pData;
public int errorNo;
}

class Program
{
[DllImport("probsoln.dll")] private static
extern void run(ref int k , ref retVar rV);
static void Main(string[] args)
{
retVar rV = new retVar();
rV.errorNo = 1;
rV.pData = 0;
int k = 5;
run(ref k , ref rV); // error when returning here
Console.WriteLine("prog finished!! k = " + k);
}
}
}

the c++ dll code is:
#define WINVER 0x0502
#ifndef _AFXDLL
#define _AFXDLL
#endif
#include <iostream>
#include <afxdisp.h>

struct retVar
{
public:
VARIANT* getPData() {return pData;}
int getErrorNo() {return errorNo;}
void setPData(VARIANT* x) {pData = x;}
void setErrorNo(int n) {errorNo = n;}
private:
VARIANT* pData;
int errorNo;
};

using namespace std;

extern "C" __declspec(dllexport) void run(int* k , retVar* rV)
{
cout << "in dll " << endl;
SAFEARRAYBOUND pSB[] = {(unsigned long)4 , 1 ,
(unsigned long)4 , 1}; // number of elts , lower bound
SAFEARRAY* pSA = SafeArrayCreate(VT_R8 , 2 , pSB);
double* saVals; // data in safe array
SafeArrayAccessData(pSA , (void**)&saVals);
*k = 3;

for (size_t i = 0; i < 4; ++i)
for (size_t j = 0; j < 4; ++j)
saVals[i * 4 + j] = (double)(i + j);
SafeArrayUnaccessData(pSA);
rV->setErrorNo(2);
VariantClear(rV->getPData());
rV->getPData()->vt = VT_ARRAY | VT_R8; // removing this and next line
rV->getPData()->parray = pSA; // and prog runs
cout << " out of dll " << rV->getPData()->parray->rgsabound->cElements << endl;
return;
}

can anyone help please: