using System; using System.Runtime.InteropServices;/* Provides mappings between C# and native code */ namespace NumericalAlgorithmsGroup { class Simplex { /* Delegate object, note that: 1) the scalar parameter is 'ref' 2) IntPtr is equivalent to the C void pointer. During a callback Fortran passes a void pointer as the parameter to C#. The memory pointed to by the IntPtr is reclaimed using Marshal.copy */ public delegate void NAG_E04CC_FUNCT (ref int n, IntPtr xc_ptr, ref double fc); public delegate void NAG_E04CC_MONIT (ref double fmin, ref double fmax, IntPtr sim_ptr,/* double [,] sim,*/ ref int n, ref int ldsim, ref int ncall); static int imonit = 0; [DllImport("FLDLL214Z_nag.dll")] /* Import from DLL, the C# compiler provides a rudimentry check of the signature */ public static extern void E04CCF(ref int n, double [] x, ref double f, ref double tol, ref int iw, double [] w1, double [] w2, double [] w3, double [] w4, double [] w5, double [] w6, NAG_E04CC_FUNCT funct, NAG_E04CC_MONIT monit, ref int maxcal, ref int ifail); public static void Main() { /* Create delegate objects */ NAG_E04CC_FUNCT FUNCT = new NAG_E04CC_FUNCT(myfunct); NAG_E04CC_MONIT MONIT = new NAG_E04CC_MONIT(mymonit); int n = 2; double [] x = {-1.0, 1.0}; double f=99.0; double tol = 1.0e-6; int iw = n+1; double [] w1 = new double[n]; double [] w2 = new double[n]; double [] w3 = new double[n]; double [] w4 = new double[n]; double [] w5 = new double[iw]; double [] w6 = new double[iw*n]; int ifail = 1; int maxcal = 100; // imonit = 1; E04CCF(ref n, x, ref f, ref tol, ref iw, w1, w2, w3, w4, w5, w6, FUNCT, MONIT, ref maxcal, ref ifail); if (ifail != 0) { // throw exception } Console.WriteLine("Final value = {0, 7:f4}\n at the point {1, 7:f4}, {2, 7:f4}", f, x[0], x[1]); } public static void myfunct(ref int n, IntPtr xc_ptr, ref double fc) { double [] xc = new double[n]; Marshal.Copy( xc_ptr, xc, 0, n ); fc = Math.Exp(xc[0]) * (xc[0] * 4.0 * (xc[0] + xc[1]) + xc[1] * 2.0 * (xc[1] + 1.0) + 1.0); } public static void mymonit(ref double fmin, ref double fmax, IntPtr sim_ptr,/* double [,] sim,*/ ref int n, ref int ldsim, ref int ncall) { double [] sim = new double[ldsim*n]; Marshal.Copy( sim_ptr, sim, 0, ldsim*n );/* Marshal.copy does not allow the type of sim to be [,] */ if (imonit != 0 ) { Console.WriteLine("After {0} calls, the Simplex is ", ncall); for (int i=0; i