Example 27 Example
PROGRAM main
!This program passes to character variables to a C routine,
!which overwrites them. This program displays the
!character variables before and after the call.
!Initialize the character variables and append null
!characters so that C can process them. CHARACTER(LEN=10) :: first_name = "Pete"//CHAR(0) CHARACTER(LEN=15) :: last_name = "Seeger"//CHAR(0)
!Note that character variables, like arrays, are passed by
!reference in both languages. There’s no need to use the
!%REF
!provides an extra argument for the "hidden" length
!parameter. To suppress passing that parameter, use %REF. CALL get_string(first_name, last_name)
PRINT 20, first_name, last_name
20 FORMAT(/, 'The names passed back to Fortran: ', A, 1X, A) END PROGRAM main
Example 28 Example
#include <stdio.h> #include <string.h>
void fix_string_for_f90(char s[], int len);
/* get_string: overwrites the string arguments fname and lname;
*fname_len and lname_len are the hidden length arguments, which
*are implicitly passed by Fortran with each string argument.
*/
void get_string(char fname[], char lname[], int fname_len, int lname_len)
{
printf(“The names passed to C: %s %s\n", fname, lname);
printf(“\nEnter the first and last names of a banjo player: "); scanf(“%s%s”, fname, lname);
fix_string_for_f90(fname, fname_len); fix_string_for_f90(lname, lname_len);
}
/* fix_string_for_f90: replaces the null at the end of the string
*in the character array and th a blank and blank fills the
*remaining elements up to len; this processing is necessary if
*the character variable is to be manipulated by Fortran
*/
void fix_string_for_f90(char s[], int len)
{
int i;
for (i = strlen(s); i < len; i++) s[i] = ' ';
}
Below are the command lines to compile, link, and execute the program, followed by the output from a sample run.
$ cc
$ f90 pass_chars.f90 get_string.o $ a.out
The names passed to C: Pete Seeger
Enter the first and last names of a banjo player: Wade Ward
The names passed back to Fortran: Wade Ward
File handling
A Fortran unit number cannot be passed to a C routine to perform I/O on the associated file; nor can a C file pointer be used by a Fortran routine. However, a file created by a program written
120 Calling C routines from HP Fortran