• Fortran passes the length of strings as hidden arguments. Using "String" type in C# to pass strings to Fortran, and add string lengths as addtional arguments after the actual arguments.
• Using StringBuilder to pass Fortran strings to C#. The Fortran strings shall be null terminated, and the StringBuilder in C# shall has enough capacity.
• In C# prototype declaration, the DllImport property "CharSet" shall be set to "CharSet=CharSet.Ansi".
1. The Fortran code:
! This sample demonstarte passing strings from other languages to Fortran
Subroutine WriteStrings(str1,str2)
!DEC$ ATTRIBUTES DLLEXPORT, StdCall, Reference, Alias:'WriteStrings'::WriteStrings
Character*(*) str1,str2
Write(*,*) 'Printed by Fortran subrotine ...'
Write(*,*) str1
Write(*,*) str2
End subroutine
! This sample demonstarte passing strings to other languages from Fortran
Subroutine GetStrings(str1,str2)
!DEC$ ATTRIBUTES DLLEXPORT, StdCall, Reference, Alias:'GetStrings'::GetStrings
Character*(*), intent(out) :: str1
Character*(*), intent(out) :: str2
! String chall be null terminated
str1='The first string from Fortran subroutine'C
str2='The second string from Fortran subroutine'C
End subroutine
2. The C# interface class:
public class ForLib
{
[DllImport("FStringDLL.dll",CallingConvention=CallingConvention.StdCall,CharSet= CharSet.Ansi)]
public static extern void WriteStrings(String str1,String str2, int LenStr1, int LenStr2);
[DllImport("FStringDLL.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern void GetStrings(StringBuilder sb1, StringBuilder sb2, int Len1,int Len2);
}
3. The C# test code:
static void Main(string[] args)
{
String str1="C# string: Hello, world!";
String str2 = "C# string: Another string";
ForLib.WriteStrings(str1, str2, str1.Length, str2.Length);
// The capacity of strings should be enough
int Len1 = 1024, Len2 = 1024;
StringBuilder sb1 = new StringBuilder(Len1);
StringBuilder sb2 = new StringBuilder(Len2);
ForLib.GetStrings(sb1, sb2, Len1, Len2);
Console.WriteLine("Printed by C# ...");
Console.WriteLine(sb1.ToString());
Console.WriteLine(sb2.ToString());
Console.ReadKey();
}