Calling a FORTRAN Subroutine from C

The example below demonstrates a C main module calling a FORTRAN subroutine, MAXPARAM. This subroutine adjusts the lower of two arguments to be equal to the higher argument.

/* C source file - calls FORTRAN subroutine

* Compile in medium or large model

*/

extern void __fortran maxparam( int __near * I, int __near * J );

/* Declare as void, because there is no return value.

* FORTRAN keyword causes C to use FORTRAN/Pascal

* calling and naming conventions.

* Two integer parameters, passed by near reference.

*/

main()

{

int a = 5;

int b = 7;

printf( “a = %d, b = %d”, a, b );

maxparam( &a, &b );

printf( “a = %d, b = %d”, a, b );

}

C FORTRAN source file, subroutine MAXPARAM

C

$NOTRUNCATE

SUBROUTINE MAXPARAM (I, J)

INTEGER*2 I [NEAR]

INTEGER*2 J [NEAR]

C

C I and J received by near reference,

C because of NEAR attribute

C

IF (I .GT. J) THEN

J = I

ELSE

I = J

ENDIF

END

In the previous example, the C program adopts the naming convention and calling convention of the FORTRAN subroutine. The two programs must agree on whether parameters are to be passed by reference or by value. The following keywords affect how the two programs interface:

The __fortran keyword directs C to call maxparam with the FORTRAN/Pascal naming convention (as MAXPARAM); __fortran also directs C to call maxparam with the FORTRAN/Pascal calling convention.

Since the FORTRAN subroutine MAXPARAM may alter the value of either parameter, both parameters must be passed by reference. In this case, near reference was chosen; this method is specified in C by the use of near pointers, and in FORTRAN by applying the NEAR keyword to the parameter declarations.

Far reference could have been specified by using far pointers in C. In that case, you would not declare the FORTRAN subroutine MAXPARAM with the NEAR keyword. If you compile the FORTRAN program in medium model, declare MAXPARAM using the FAR keyword.