In the brave new world of c interoperability the standard requires that c-strings passed into a Fortran subroutine are interpreted as arrays of characters of length 1. So to use them in a Fortran program and array of characters has to be converted into a character string. So my question is what is the best way of doing this? At the moment I'm using the function below with example usage but I'm not convinced it is optimal. Thanks.
module cstr contains function c_to_f_string(s) result(str) use iso_c_binding character(kind=c_char,len=1), intent(in) :: s(*) character(len=:), allocatable :: str integer i, nchars i = 1 do if (s(i) == c_null_char) exit i = i + 1 end do nchars = i - 1 ! Exclude null character from Fortran string allocate(character(len=nchars) :: str) str = transfer(s(1:nchars), str) end function c_to_f_string subroutine pstr(s) bind(c,name='pstr') use iso_c_binding use cstr character(kind=c_char,len=1), intent(in) :: s(*) character(len=:), allocatable :: str integer i, nchars write(*,'(a)') c_to_f_string(s) end subroutine pstr
extern "C" { void pstr(const char*); }; int main(int argc, char** argv) { if (argc > 1) { pstr(argv[1]); } else { pstr("hello"); } return 0; }