title: AccessViolationException calling Fortran from C#
body: <p>I'm trying to wrap the glmnet library (<a href="http://cran.r-project.org/web/packages/glmnet/index.html" rel="nofollow">http://cran.r-project.org/web/packages/glmnet/index.html</a>) so I can solve <s>models</s> sparse general linear models in C#. However, the original function has a somewhat 20 parameters, so I started (completely new to Fortran) with a tiny subroutine for testing how to pass data. Unfortunately I always get an AccessViolationException.</p>
  
  <p>Here's the code:</p>
  
  <p>The Fortran subroutine. I compile it into a dll using the gfortran compiler that comes with Rtools (<a href="http://cran.r-project.org/bin/windows/Rtools/" rel="nofollow">http://cran.r-project.org/bin/windows/Rtools/</a>), using the -m64 option (yes, 64bit is neccessary since I handle quite big chunks of data). Yes, the use of i could lead to out-of-bounds... but this is just for testing.</p>
  
  <pre><code>subroutine testaaa  (f,i,fa,ia)
  real fa(i)                                                      
  integer ia(i)
  ia(1) = 1337
  ia(i) = 666
  fa(1) = 8.15
  fa(i) = 333
  end subroutine testaaa
  </code></pre>
  
  <p>The C# PInvoke code:</p>
  
  <pre><code>[DllImport("ftest.dll", EntryPoint = "testaaa_", CallingConvention = CallingConvention.StdCall)]
  public static extern void Test(
      [MarshalAs(UnmanagedType.R4)] float f,
      [MarshalAs(UnmanagedType.I4)] int i,
      IntPtr fa,
      IntPtr ia);
  </code></pre>
  
  <p>And here is how it's called:</p>
  
  <pre><code>var fa = new float[4];
  var ia = new int[4];
  IntPtr faPtr = Marshal.AllocHGlobal(fa.Length * sizeof(float));
  Marshal.Copy(fa, 0, faPtr, fa.Length);
  
  IntPtr iaPtr = Marshal.AllocHGlobal(ia.Length * sizeof(float));
  Marshal.Copy(ia, 0, iaPtr, ia.Length);
  
  GlmnetDllWrapper.Test(0.4f, 4,faPtr,iaPtr);
  </code></pre>
  
  <p>I also tried passing the arrays directly and giving them the [MarshalAs(UnmanagedType.LPArray)] attribute. Nothing worked for me.</p>
  
  <p>Do you have any suggestions where to start or what to change?</p>
  
  <p>Update 1:
  Even passing only the float and the int already causes the exception:</p>
  
  <pre><code>subroutine testbbb  (f,i)
  i = 815
  f = 8.15
  return
  end subroutine testbbb
  </code></pre>
  
  <p>C# Pinvoke and call are changed accordingly. What am I doing wrong?</p>