Reputation: 469
I’ve not found any posts on Stack Overflow that discuss calling C# from Fortran (I’m using Visual Studio 2010 with Intel Visual Fortran installed as well). However, there is a (very) limited # of posts[1, 2, 3 ] that discuss calling C/C++ from fortran.
In one of the responses to these posts, it was suggested that calling C++ from Fortran is trickier than calling C, which raised my suspicions that C# may be trickier yet? Lacking a foundation in C/C++/C#, I’m wondering if the procedures laid out for C/C++ are applicable to C#?
One commonality I noticed among these posts was that the intrinsic module called ISO_C_BINDING was needed. After reading a bit more about it here, it wasn’t clear to me that ISO_C_BINDING would allow me to pass a couple of 2D-arrays worth of information to a program (compiled as a DLL) written in C#, call some ‘events’ (analogous to functions?), and finally get back a 2D-array of information from C# , before moving on about my business in Fortran.
If familiar with both Fortran and C#, could you please tell me if ISO_C_BINDING is adequate to the task? I’ve not gotten that sense from the information I’ve listed above. If anyone has a working example that includes passing arrays between C# and Fortran, as well as calling C# functions from Fortran, I would very much appreciate the opportunity to look it over as a template for how I might proceed. Thanks, Eric
Upvotes: 2
Views: 873
Reputation: 9074
Fortran code:
function TestPass (floatArray) result (iRes)
implicit none
dll_export :: TestPass ! export function name
integer :: Ires
real, intent (in out) :: floatArray
dimension floatArray(5)
iRes = 0 ! Assign function result
open (5,FILE='output.txt')
write (5, 100) floatArray(3)
floatArray(0) = 0.0
floatArray(1) = 1.1
floatArray(2) = 2.2
floatArray(3) = 3.3
floatArray(4) = 4.4
! correct values are written to file here...
open (5,FILE='output.txt')
write (5, 100) floatArray(3)
100 format(5X,'got here',5X,F3.3)
close (5)
end function
C# code:
static extern int TestPass (
[MarshalAs(UnmanagedType.LPArray, SizeConst=5,
ArraySubType=UnmanagedType.R4)]
float [] yields);
private void BtnTestClick(object sender, System.EventArgs e)
{
float [] floatArray = new float[5] {9.9F, 9.9F, 9.9F, 9.9F, 9.9F};
TestPass(floatArray);
// floatArray.Length == 0 after the function call
for ( int i = 0; i < floatArray.Length; i++ )
Trace.WriteLine(floatArray[i]);
}
Also refer this link:
http://software.intel.com/en-us/articles/calling-fortran-function-or-subroutine-in-dll-from-c-code
You can also refer some theory about it:
http://www.ibiblio.org/pub/languages/fortran/ch2-4.html
Upvotes: 2