Creating a FORTRAN interface to a C function that returns a char*

后端 未结 7 1359
天涯浪人
天涯浪人 2020-12-01 10:11

I\'ve been held up on this for about a week, now, and have searched forum after forum for a clear explanation of how to send a char* from C to FORTRAN. To make the matter m

7条回答
  •  隐瞒了意图╮
    2020-12-01 10:20

    This thread is a little old, but since I had a similar problem (and probably others will), I post a answer anyway.

    The codes posted above will cause a segmentation fault if, for some reason, the C string is null. In addition, there is no need to return a 255-chars string (which will probably need to be trimmed before used), as Fortran 2003/2008 supports functions returning allocatable entities. Using all the information posted above, I ended up with the following function, which gets a C string (pointer), and returns the corresponding Fortran string; If the C string is null, it returns "NULL", similarly to C's "(null)" printed in similar cases:

    function C_to_F_string(c_string_pointer) result(f_string)
    use, intrinsic :: iso_c_binding, only: c_ptr,c_f_pointer,c_char,c_null_char
    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=255) :: aux_string
    integer :: i,length
    call c_f_pointer(c_string_pointer,char_array_pointer,[255])
    if (.not.associated(char_array_pointer)) then
      allocate(character(len=4)::f_string); f_string="NULL"; return
    end if
    aux_string=" "
    do i=1,255
      if (char_array_pointer(i)==c_null_char) then
        length=i-1; exit
      end if
      aux_string(i:i)=char_array_pointer(i)
    end do
    allocate(character(len=length)::f_string)
    f_string=aux_string(1:length)
    end function C_to_F_string
    

提交回复
热议问题