Iso_c_binding: interface to a C function returning a string

For most people in scientific and technical computing who primarily aspire to bring about meaningful advances in their chosen domains rather than get into the weeds of stack and heap allocations and memory leaks and dangled pointers and so forth, functions in C, C++ whose return values are pointers are fraught.

So if it’s possible for library authors who may have more expertise in C, C++ to stay away from such return values, especially with char * and strings where the semantics in C gets further tricky, that will be rather kind of them toward the users of their libraries. And if the users are expected to be Fortranners as well, such expert library authors can use the enhanced interoperability facility introduced in Fortran 2018 to make it further easier for them. Here is a simple how-to example of this from the Intel forum.

But now if a reauthoring of the C function is not viable, then eschewing some type safety by using type(c_ptr) as the return type is an option, as shown by @ivanpribec above.

As commented by @ivanpribec re: string copy, if it is to be avoided, then employ the C library function strlen that can be readily invoked from Fortran when it is interoperating with a C companion processor:

 ..
    character(len=:,kind=c_char), pointer :: buffer
    integer(c_int) :: lenbuffer
    type(c_ptr) :: cstring
    cstring = nlopt_algorithm_name( a )
    lenbuffer = strlen( cstring )  ! Elided is the interface for this C library function
    block
          character(len=lenbuffer, kind=c_char), pointer :: s
          call c_f_pointer(cstring, s)
          buffer => s
    end block
    print *, "Fortran string: ", buffer
..

Edit: removed the ‘function … end function’ construct from the code snippet per @ivanpribec’s comment.

2 Likes