next up previous 252
Next: Building the Program
Up: Cookbook
Previous: Calling C from FORTRAN


Calling FORTRAN from C

Why would you want to call a FORTRAN subprogram from a C routine? Typically this would be because you want to use a precompiled library of routines that were written in FORTRAN. The NAG library is a prime example. This can be bought in a C callable version, but this is not available on Starlink machines.

To see how to call FORTRAN from C, let us consider the above example, but now with the roles of FORTRAN and C exchanged.

Example - Calling FORTRAN from C.
C program:
      #include "f77.h"

      #define FLINE_LENGTH 80
      
      extern F77_SUBROUTINE(silly2)( REAL(a), REAL(b), INTEGER(i), INTEGER(j),
         CHARACTER(line), INTEGER(line_l), LOGICAL(x) TRAIL(line) );

      main()
      {
         DECLARE_INTEGER(i);
         DECLARE_INTEGER(j);
         DECLARE_INTEGER(fline_l);
         DECLARE_REAL(a);
         DECLARE_REAL(b);
         DECLARE_LOGICAL(x);
         DECLARE_CHARACTER(fline,FLINE_LENGTH);

         char line[FLINE_LENGTH+1];

         fline_l = FLINE_LENGTH;

         i = 1;
         a = 5.0;
         x = F77_FALSE;

         F77_CALL(silly2)( REAL_ARG(&a), REAL_ARG(&b), INTEGER_ARG(&i),
           INTEGER_ARG(&j), CHARACTER_ARG(fline), INTEGER_ARG(&fline_l),
           LOGICAL_ARG(&x) TRAIL_ARG(fline) );

         cnfImprt( fline, FLINE_LENGTH, line );

         printf( "%s\n", line );
      }
FORTRAN function:
      SUBROUTINE SILLY2( A, B, I, J, LINE, LINE_L, X )
      REAL A, B
      INTEGER I, J
      CHARACTER * ( * ) LINE
      INTEGER LINE_L
      LOGICAL X

      IF( X ) THEN
        B = A
        J = I
      ELSE
         LINE = 'This is a string'
      END IF

      END

In the above C main program, the variable fline_l is declared and set equal to the constant FLINE_LENGTH. At first sight this is unnecessary. However, this is not the case, as we need to pass the value of FLINE_LENGTH to the subroutine and it is not possible to pass constants to FORTRAN subroutines. Only variables can be passed.



next up previous 252
Next: Building the Program
Up: Cookbook
Previous: Calling C from FORTRAN

CNF and F77 Mixed Language Programming -- FORTRAN and C
Starlink User Note 209
P.M. Allan
A.J. Chipperfield
R.F. Warren-Smith
19 January 2000
E-mail:ussc@star.rl.ac.uk