Passing character types between languages

One difficult aspect of interlanguage calls is passing character strings between languages.

The difficulty is due to the following underlying differences in the way that different languages represent such entities:
  • The only character type in Fortran is CHARACTER, which is stored as a set of contiguous bytes, one character per byte. The length is not stored as part of the entity. Instead, it is passed by value as an extra argument at the end of the declared argument list when the entity is passed as an argument. The size of the argument is 4 or 8 bytes, depending on the compilation mode used (32- or 64-bit, respectively).
  • Character strings in C are stored as arrays of the type char. A null character indicates the end of the string.
    Note: To have the compiler automatically add the null character to certain character arguments, you can use the -qnullterm option.
If you are writing both parts of the mixed-language program, you can make the C routines deal with the extra Fortran length argument, or you can suppress this extra argument by passing the string using the %REF function. If you use %REF, which you typically would for pre-existing C routines, you need to indicate where the string ends by concatenating a null character to the end of each character string that is passed to a C routine:
! Initialize a character string to pass to C.
               character*6 message1 /'Hello\0'/
! Initialize a character string as usual, and append the null later.
               character*5 message2 /'world'/

! Pass both strings to a C function that takes 2 (char *) arguments.
               call cfunc(%ref(message1), %ref(message2 // '\0'))
               end

For compatibility with C language usage, you can encode the following escape sequences in Open XL Fortran character strings:

Table 1. Escape sequences for character strings
Escape Meaning
\b Backspace
\f Form feed
\n New-line
\t Tab
\0 Null
\' Apostrophe (does not terminate a string)
\" Double quotation mark (does not terminate a string)
\ \ Backslash
\x x, where x is any other character (the backslash is ignored)

If you do not want the backslash interpreted as an escape character within strings, you can compile with the -qnoescape option.