This Fortran-based function approach is neat and tidy, and is well-suited when a string has not yet been set (or memory allocated for it) in routine C. Note that you do not need to pass a string length argument or use an array of the intended size to create / return a string value. 1
The Fortran character string constant is used, so this function can be reused for any string.
The integer argument is also passed to the Fortran function to demonstrate, for example, how you can specify what the desired response should be.
Note that in this example, “intent (out)” is used to indicate that the integer argument does not need to be determined before passing, but it can be updated before it is returned. Therefore, you can change its value and return it to the calling program to use it as a “return code” instead.
Fortran Function
! f_string.f90 ! Called from C routine as: `myString = get_string(rc)` function get_string(c_rc) bind(c, name='get_string') use, intrinsic :: iso_c_binding implicit none integer(c_int), intent(out) :: c_rc ! <- Pass by reference; acts as return code in this example. type(c_ptr) :: get_string ! <- C_PTR to pass back to C character(len=:), allocatable, target, save :: fortstring ! <- Allocatable/any length is fine fortstring = "Append C_NULL_CHAR to any Fortran string constant."
Program C
// c_string.c
Compilation, call, output:
ifort /c f_string.f90 icl c_string.c /link f_string.obj c_string.exe
1 It is also easy to compile without warning (what happens to the OP solution without the change that I suggested in my comments).
source share