Intel® Fortran Compiler Classic and Intel® Fortran Compiler Developer Guide and Reference

ID 767251
Date 6/24/2024
Public

A newer version of this document is available. Customers should click here to go to the newest version.

Document Table of Contents

Characters

The C language does not have character strings. Instead, it has arrays of single characters. You must represent this type of character string in Fortran.

A kind value is defined, C_CHAR, which 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. ! Easiest way to call c_append: call c_append (F_C_STRING ('Intel Fortran')) ! Alternate way to call c_append 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), target :: string integer s_len ! Length of string character(LEN=:, C_CHAR), pointer :: string_pointer character(100), pointer :: string1 character(100) :: string2 ! Easiest way to convert the array to a character pointer. ! LEN(string_ptr) will be set to INDEX(string, C_NULL_CHAR) – 1. call C_F_STRPOINTER (string, string_ptr) print *, string_ptr ! Another 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;
}