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
I have also struggled with calling a C routine that returns a string and the answers above has been very useful but as I know almost nothing of C and the answers are slightly confusing I just wanted to contribute my solution which uses a C pointer, I did not manage to make use any of the other proposals above. The C program I call opens a separate window to browse for a file name.
program test
use iso_c_binding
implicit none
! A C function that returns a string need a pointer to the array of single char
type (c_ptr) :: C_String_ptr
! This is the Fortran equivalent to a string of single char
character (len=1, kind=c_char), dimension(:), pointer :: filchar=>null()
! Interface to a C routine which opens a window to browse for a file to open
interface
function tinyopen(typ) bind(c, name="tinyopen")
use iso_c_binding
implicit none
integer(c_int), value :: typ
type (C_Ptr) :: tinyopen
end function tinyopen
end interface
character (len=256) :: filename
integer typ,jj
typ=1
C_String_ptr = tinyopen(typ)
! convert C pointer to Fortran pointer
call c_f_pointer(C_String_ptr,filchar,[256])
filename=' '
if(.not.associated(filchar)) then
! if no characters give error message
write(*,*)'No file name'
else
! convert the array of single characters to a Fortran character
jj=1
do while(filchar(jj).ne.c_null_char)
filename(jj:jj)=filchar(jj)
jj=jj+1
enddo
endif
write(*,*)'Text is: ',trim(filename)
end program test
Hopefully this example will make it easier for the next one with the same problem.