c2s Function

public function c2s(c_string_pointer) result(f_string)

NAME

  c2s(3f) - [M_strings:ARRAY] convert C string pointer to Fortran
  character string
  (LICENSE:PD)

SYNOPSIS

function c2s(c_string_pointer) result(f_string)

 type(c_ptr), intent(in)       :: c_string_pointer
 character(len=:), allocatable :: f_string

DESCRIPTION

Given a C pointer to a character string return a Fortran character
string.

OPTIONS

c_string_pointer  C pointer to convert

RETURNS

f_string          Fortran character variable to return

EXAMPLE

AUTHOR

John S. Urban

LICENSE

Public Domain

Arguments

Type IntentOptional Attributes Name
type(c_ptr), intent(in) :: c_string_pointer

Return Value character(len=:), allocatable


Contents

Source Code

c2s

Source Code

function c2s(c_string_pointer) result(f_string)
! gets a C string (pointer), and returns the corresponding Fortran string;
! If the C string is null, it returns "NULL", similar to C's "(null)" printed in similar cases:
use, intrinsic :: iso_c_binding, only: c_ptr,c_f_pointer,c_char,c_null_char

! ident_28="@(#) M_strings c2s(3f) copy pointer to C char array till a null is encountered to a Fortran string up to 4096 characters"

integer,parameter                             :: max_length=4096
type(c_ptr), intent(in)                       :: c_string_pointer
character(len=:), allocatable                 :: f_string
character(kind=c_char), dimension(:), pointer :: char_array_pointer => null()
character(len=max_length)                            :: aux_string
integer                                       :: i,length=0

   call c_f_pointer(c_string_pointer,char_array_pointer,[max_length])
   if (.not.associated(char_array_pointer)) then
     allocate(character(len=4)::f_string)
     f_string="NULL"
     return
   endif
   aux_string=" "
   do i=1,max_length
     if (char_array_pointer(i)==c_null_char) then
       length=i-1
       exit
     endif
     aux_string(i:i)=char_array_pointer(i)
   enddo
   allocate(character(len=length)::f_string)
   f_string=aux_string(1:length)

end function c2s