Fixing stack overflow error for C# calling a fortran dll
See the question and my original answer on StackOverflowThe Fortran compiler exposes the structure as a reference. This can be seen after (Intel here) compilation and disassembly below as GRANDPARANT *GP
:
So the C# declaration should this instead:
public static extern void SizeCheck(ref GrandParent gp);
PS: the calling convention is not important in x64 (fastcall
is by default)
To fix the stack overflow, you can either 1) change the maximum stack size compiled into your executable by using EditBin from the Visual Studio SDK like this for example (with 10Mb of stack):
EditBin.exe <your.exe> /stack:10000000
or 2) decide to marshal the big object "manually" like this:
var gp = new GrandParent();
var ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf<GrandParent>());
try
{
Marshal.StructureToPtr(gp, ptr, false);
Natives.SizeCheck(ptr);
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
With the DllImport statement modified like this:
[DllImport("FortranLib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void SizeCheck(IntPtr gp);