have defined a wrapper around it in C# which uses some delegates:
#region Delegates and Marshalling to call solvopt
public delegate double funCallback(double[] x);
public delegate double funcCallback(double[] x);
public delegate void gradCallback(double[] x, double[] v);
public delegate void gradcCallback(double[] x, double[] v);
[DllImport("SolvOpt_C.dll")] //, EntryPoint="useFunc")]
extern static unsafe double* solvopt(UInt16 n, double[] x, funCallback
fun, gradCallback grad, double[] options, funcCallback func,
funcCallback gradc);
public static unsafe double[] SolvOptWrapper(UInt16 n, double[] x,
funCallback fun, gradCallback grad, double[] options, funcCallback
func, funcCallback gradc)
{
double* us_Ret;
double[] retVal = new double[n + 1];
int it = 0;
us_Ret = solvopt(n, x, fun, grad, options, func, gradc);
retVal.Initialize();
for ( it = 0 ; it < n+1 ; ++it )
retVal[it] = us_Ret[it];
return retVal;
}
#endregion
static unsafe double funTest(double[] x)
{
return ( Math.Sqrt(x[0] - 4) + Math.Sqrt(x[1] - 3));
}
public static void TestDelegates()
{
UInt16 n;
double[] x;
funCallback fun = new funCallback(funTest);
gradCallback grad = null;
funcCallback func = null;
funcCallback gradc = null;
double[] solvopt_options = new double[13]{-1.0e+0 , 1.0e-4 , 1.0e-6 ,
15.0e+3 , 0.0e+0,1.0e-8 , 2.5e+0 , 1.0e-11 , 0.0e+0 , 0.0e+0 , 0.0e+0 ,
0.0e+0 , 0.0e+0};
n = 2;
x = new double[2]{ 2.0 , 1.0 };
SolvOptWrapper(n, x, fun, grad, solvopt_options, func, gradc);
}
When I call TestDelegate I get this error:
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in ConsoleTester.exe
Additional information: Index was outside the bounds of the array.
From what I understand the debugger is telling me that the double[2]
that I pass in parameter is converted to a double* when calling the C
function.
However when the C function (solvopt) calls the Callback function by
the delegate (funTest) the parameter is passed as double[1], probably
because it has no idea about the length of the array.
Anybody knows how I can solve this problem knowing that I cannot know
the size of this array before the function is called (the size is the
UInt16 n).
Cheers
Anthony