module iso_c_utilities use iso_c_binding ! intrinsic module interface pure function strlen(string) result(len) bind(c,name="strlen") use iso_c_binding type(c_ptr), value, intent(in) :: string ! a c pointer integer(c_int) :: len end function strlen end interface contains function c_f_string(cptr) result(str) type(c_ptr), intent(in) :: cptr ! the c address character(len=:), allocatable :: str integer :: i character(kind=c_char), dimension(:), pointer :: fptr allocate(character(len=strlen(cptr)) :: str) if(c_associated(cptr)) then call c_f_pointer(fptr=fptr, cptr=cptr, shape=[strlen(cptr)]) do i = 1, strlen(cptr) str(i:i) = fptr(i) end do end if end function c_f_string end module iso_c_utilities module data use iso_c_binding use iso_c_utilities private character(c_char), target :: c_str bind(C, name="script") :: c_str public get_text contains function get_text() character(len=:), allocatable :: get_text get_text = c_f_string(c_loc(c_str)) end function get_text end module data program text use data use iso_c_binding use iso_c_utilities character(len=:), allocatable :: str str = get_text() print *, "[[" print *, str print *, "]]" print *, len(str) end program text