Intel® Fortran Compiler 17.0 Developer Guide and Reference
A discrepancy occurs when working with C and Fortran character strings: C strings are null-terminated while Fortran strings have known lengths. A C routine that returns a character string will be returning a pointer to a null-terminated string. A Fortran routine will not have any knowledge of the string’s length.
If a Fortran routine is returning a string to a C program, the Fortran program must null-terminate the string.
The following shows the Fortran code that declares interfaces to a C routine and calls the C routine. In the example, the pointer returned by the C routine can be passed along to another C routine. However, it is not usable by Fortran as-is since Fortran has no knowledge of the string's length.
Fortran Code Example |
---|
|
Called C Routine Example |
---|
#include <stdio.h> char *my_croutine1 (int input) { static char temp[30]; temp[0] = '\0'; sprintf(temp, "in routine, you said %d", input); return temp; } void my_cprint (char *string) { printf ("cprint says %s\n", string); return; } |
The example above shows the C code used to call a Fortran routine. The Fortran routine returns a string that is then printed by the C program. As shown in the example, it is relatively straightforward to pass a string back to C from Fortran. Additionally, the string can be easily used by the C program because it is NULL-terminated.
In the above example, the following restrictions and behaviors apply:
The function's length and result do not appear in the call statement; they are added by the compiler.
The called routine must copy the result string into the location specified by result; it must not copy more than length characters.
If fewer than length characters are returned, the return location should be padded on the right with blanks; Fortran does not use zeros to terminate strings.
The called procedure is type void.
The following shows the C code used to call a Fortran routine; the Fortran routine returns a string that is then printed by the C program.
C Code Example |
---|
#include <stdio.h> char *GetFortranWords(void); int main() { printf ("Fortran says this: %s\n", GetFortranWords()); return 0; } |
Called Fortran Routine Example |
---|
|