The answer provided by @John Bollinger is correct. Fortran treats strings entirely differently from C. Here is an example code that I wrote a few days ago, which passes a char array from C to Fortran, then Fortran makes it lower-case and returns the result to C,
module String_mod
implicit none
contains
subroutine getLowerCase(StrVec,StrVecLowerCase,lenStrVec) bind(C, name="getLowerCase")
use, intrinsic :: iso_c_binding, only: c_char, c_null_char, c_size_t
use, intrinsic :: iso_fortran_env, only: IK => int32
integer(c_size_t), intent(in), value :: lenStrVec
character(len=1,kind=C_char), intent(in) :: StrVec(lenStrVec)
character(len=1,kind=C_char), intent(inout) :: StrVecLowerCase(lenStrVec)
integer(IK), parameter :: duc = ichar('A') - ichar('a')
character :: ch
integer(IK) :: i
write(*,"(*(g0))") "From Inside Fortran@getLowerCase(): StrVec = ", (StrVec(i),i=1,lenStrVec)
write(*,"(*(g0))") "From Inside Fortran@getLowerCase(): lenStrVec = ", lenStrVec
do i = 1, lenStrVec
ch = StrVec(i)
if (ch>='A' .and. ch<='Z') ch = char(ichar(ch)-duc)
StrVecLowerCase(i) = ch
end do
end subroutine getLowerCase
end module String_mod
and here is the C code calling Fortran,
#include <stdio.h>
// Fortran function's prototype
extern void getLowerCase(char [], char [], size_t );
int main(void)
{
char StrVec[] = "HELLO FORTRAN! YOU ROCK!";
size_t lenStrVec = sizeof(StrVec) / sizeof(StrVec[0]);
char StrVecLowerCase[ lenStrVec ];
getLowerCase( StrVec
, StrVecLowerCase
, lenStrVec
);
printf("From Inside C: %s\n", StrVecLowerCase);
return 0;
}
Compiling with Intel Fortran/C compiler gives,
$ ifort -c String_mod.f90
$ icl -c main.c
$ icl String_mod.obj main.obj -o a.exe
$ a.exe
From Inside Fortran@getLowerCase(): StrVec = HELLO FORTRAN! YOU ROCK!
From Inside Fortran@getLowerCase(): lenStrVec = 25
From Inside C: hello fortran! you rock!
The simplest Fortran-2003 approach to string interoperation is to declare the Fortran strings as char arrays and pass the lengths of the arrays explicitly from C to Fortran or vice versa, as done in the example above. Note that all of the allocations happen on the C side. Fortran 2018 provides more convenient ways to pass strings (including allocatable strings) between Fortran and C, some of which require no change to the Fortran code and minimal work on the C code via ISO_Fortran_binding.h
. See, for example, this page.