Intel® Fortran Compiler 16.0 User and Reference Guide

Characters

The C language does not have character strings. Instead, it has arrays of single characters, so this is how you must represent a character string in Fortran.

There is a kind value defined, C_CHAR, corresponding to the C char type. However, only character variables with a length of one (1) are interoperable.

The following shows a Fortran program passing a string to a C routine and the C routine calling a Fortran routine with a new string.

Fortran Program Example

program demo_character_interop
    use, intrinsic :: iso_c_binding
    implicit none
    
    interface
    subroutine c_append (string) bind(C)
    character(len=1), dimension(*), intent(in) :: string
    end subroutine c_append
    end interface
    
    ! Call C routine passing an ordinary character value
    ! The language allows this to match an array of
    ! single characters of default kind
    call c_append('Intel Fortran'//C_NULL_CHAR)
end program demo_character_interop

subroutine fort_print (string) bind(C)
    use, intrinsic :: iso_c_binding
    implicit none
    
    ! Must declare argument as an array of single characters
    ! in order to be "interoperable"
    character(len=1), dimension(100), intent(in) :: string
    integer s_len ! Length of string
    character(100), pointer :: string1
    character(100) :: string2
    
    ! One way to convert the array to a character variable
    call C_F_POINTER(C_LOC(string),string1)
    s_len = INDEX(string1,C_NULL_CHAR) - 1
    print *, string1(1:s_len)
    
    ! Another way to convert
    string2 = TRANSFER(string,string2) ! May move garbage if source length < 100
    s_len = INDEX(string2,C_NULL_CHAR) - 1
    print *, string2(1:s_len)
    
    end subroutine fort_print

C Routine Example

C module (c_append.c):
#include <string.h>
extern void fort_print(char * string); /* Fortran routine */
void c_append (char * string) {
	char mystring[100];
	strcpy(mystring, string);
	strcat(mystring, " interoperates with C");
	/* Call Fortran routine passing new string */
	fort_print (mystring);
	return;
}