title: passing an array to a function pointer from C#
body: <p>I've implemented some functions in C program and wrap it into a dll, which will be called in another C# project. One of the function in the dll takes a function pointer as an input argument, i.e., in the source code generating the dll, one of the function looks like:</p>
  
  <pre><code>void functionA(
      int* a,
      int* b,
      double *c,
      double[] inputArr,
      double[] outputtArr,
      void(*fun)(int*, int*,double[],double[])
  )
  </code></pre>
  
  <p>Inside the functionA, the inputArr will be used as input to the function pointer and outputArr will be used as the output. The inputArr should has a dimension of *a and the size of outputtArr should be *b.</p>
  
  <p>In C#, I tried to import the dll and invoke the functionA by following:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Runtime.InteropServices;
  namespace Test{    
  class Program
      {
       public delegate void costfun(ref int a, ref int b, double[] x, double[] fx);         
       static void Main(string[] args)
          {
              int a = 5, b = 3,
              double c= 1e-14
  
              double[] x = new double[5] { 1, 3, 5, 7, 9 };                              
              double[] y= new double[3] { 100, 100, 100 };
              costfun F = new costfun(fun);
            functionA(ref a, ref b,  ref c, x,y  Marshal.GetFunctionPointerForDelegate(F));
  
          }
  
          public static void fun(ref int na, ref int nb, double[] inX, double[] outY)
          {
              int i = 0;
              outY= new double[nb];
  
              if (outY.Length != nb)
              {
                  //Console.WriteLine("output incorrect");
                  return;
              }
              if (inX.Length != na)
              {
                 // Console.WriteLine("input incorrect");
                  return;
              }
              for (i = 0; i &lt; nb; i++)
              { outY[i] = inX[i] * inX[i + 1] + 1; }
          }
  
          // import the dll
          [DllImport("cdll.dll", EntryPoint = "functionA", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]    
          public static extern void functionA(int* a, int* b, double*c,double[] inputArr, double[] outputtArr, IntPtr fcpointer);
  }
  }
  </code></pre>
  
  <p>The program is successfully compiled an can be executed. yet I found during the execution, whenever the function fun is invoked from the dll, the input array inX only has a single element, that is only inX[0] is passed. If I comment the two if statement inside the function fun, visual studio will break due to an index out of bound exception occurred in the statement:</p>
  
  <pre><code>outY[i] = inX[i] * inX[i + 1] + 1; 
  </code></pre>
  
  <p>because of inX[i+1].Can anyone gives me some hints how to tackle this problem? Thanks </p>