tags:

views:

44

answers:

1

I have the following FORTRAN:

  SUBROUTINE MYSUB(MYPARAM)
  !DEC$ ATTRIBUTES DLLEXPORT::SetPaths

  CHARACTER*50 MYPARAM

  WRITE(6, *) MYPARAM

  END SUBROUTINE

Then I have the following in C#

class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder(50);
        sb.Append(@"something");
        MYSUB(sb);

        Console.ReadLine();
    }

    [DllImport(@"myCode.dll", EntryPoint = "MYSUB")]
    public static extern void MYSUB(StringBuilder input);

}

However, the WRITE in my FORTRAN shows a bunch of junk after "something." Looks like the string terminator is not being honored. Help!

+1  A: 

Strings are the trickiest datatype to interchange between different languages.

The basic Fortran string is fixed length, padded on the end with blanks. (Fortran now has variable length strings, but those would be harder to interchange.) The intrinsic "trim" is provided to suppress trailing blanks; "len_trim" to provide the length less trailing blanks.

C flags the end of a string with a null character.

I don't know how C# handles strings -- an internal variable for the length?? a terminator??

But Fortran isn't going to understand C#'s representation, it will just see the full length of the string, as declared, including, in this case, uninitialized memory. The best solution is probably to initialize the remainder of the string to blanks in C#.

M. S. B.