HP Fortran Programmer's Guide (B3908-90031; September 2011)

Calling C routines from HP Fortran
C strings
Chapter 8 195
C strings
C strings differ from Fortran character variables in two important respects:
C expects strings to be null-terminated.
For each character variable or character constant that Fortran passes to a C routine, it also passes a
hidden length argument.
The following sections discuss these differences and explain how to code for them. The last section includes
an example program.
C null-terminated string
Unlike HP Fortran programs written in C expect strings to be null-terminated; that is, the last character of a
string must be the null character ('\0'). To pass a string from Fortran to C, you must do the following:
Declare the character variable that is large enough to include the null character.
Explicitly assign the null character to the final element of the character array or use the concatenation
operator, as in the following example:
CALL csub ('a string'//CHAR(0))
If the Fortran program is going to use a string that has been passed back to it from C, then either the C
function or the Fortran subprogram should strip off the null character before Fortran tries to use it. The
example program in “Passing a string” on page 196 shows how to do this in C.
Fortran hidden length argument
For each CHARACTER*n argument passed to a Fortran subprogram, two items are actually passed as
arguments:
The address of the character argument in memory (that is, a pointer to the argument).
The argument's length in bytes. This is the “hidden” length argument that is available to the subprogram
from the stack.
To pass a string argument from Fortran to C, you must explicitly prepare the C function to receive the string
address argument and the hidden argument. The order of the address arguments in the argument list will be
the same in C as in Fortran. The hidden length 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.