HP Fortran Programmer's Guide (September 2007)

Calling C routines from HP Fortran
C strings
Chapter 8190
arguments, however, will come at the end of the list. If more than one string argument is
passed, the length arguments will follow the same order as the address arguments, but at the
end of the C’s argument list.
Note that both C and Fortran both pass strings by reference. This means that, if Fortran
passes only string arguments to C, you need not use the %VAL and %REF built-in functions to
indicate how the arguments are to be passed. For information about these functions, see
Argument-passing conventions” on page 181.
Passing a string
The example program in this section illustrates how to pass a string—which, in Fortran, is a
character variable or constant—to a C function. It also illustrates how to process a C string so
that it can be manipulated in Fortran.
The program consists of two source files:
The Fortran source file, which consists of a main program unit that declares two
initialized character variables and passes them to a C function.
The C source code, which consists of two functions:
get_string: receives the two character array arguments from Fortran and overwrites
the strings in the arrays with new strings
fix_string_for_f90: processes the string in its character array argument to replace
the null-terminating character with a blank character and to blank-fill the remaining
characters. This processing is necessary so that Fortran can manipulate the character
variable.
The get_string function has two additional arguments in its argument list, which pick up
the hidden string length arguments that Fortran implicitly passes with each string argument.
The following are example C and Fortran programs.
Example 8-7 pass_chars.f90
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