See this thread.
Another option - one I recommend - is better, higher-level code in C; it can be wrappers to existing functions.
#include <string.h>
#include "ISO_Fortran_binding.h"
static char *str = "Hello";
void getstring_c( char **string, size_t *length ) {
*string = str;
*length = strlen(*string) ;
}
// Wrapper for Fortran users
int getstr( CFI_cdesc_t *s ) {
int irc = CFI_establish(s, str, CFI_attribute_pointer, CFI_type_char,
strlen(str), (CFI_rank_t)0, NULL);
return irc;
}
Then the modern Fortran code is simply:
use, intrinsic :: iso_c_binding, only : c_int, c_char
interface
function getstr( str ) result(irc) bind(C, name="getstr")
import :: c_int, c_char
implicit none
! Argument list
character(kind=c_char, len=:), pointer, intent(out) :: str
! Function result
integer(c_int) :: irc
end function
end interface
character(kind=c_char, len=:), pointer :: s
integer(c_int) :: irc
irc = getstr( s )
if ( irc == 0 ) then
print *, "s: ", s, "; expected is Hello"
print *, "len: ", len(s), "; expected is 5"
else
print *, "getstr function returned an error."
end if
end
C:\Temp>cl /c /W3 /EHsc c.c
Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29337 for x64
Copyright (C) Microsoft Corporation. All rights reserved.c.c
C:\Temp>ifort /c /standard-semantics /warn:all /stand:f18 f.f90
Intel(R) Fortran Intel(R) 64 Compiler Classic for applications running on Intel(R) 64, Version 2021.1.2 Build 20201208_000000
Copyright (C) 1985-2020 Intel Corporation. All rights reserved.C:\Temp>link f.obj c.obj /subsystem:console /out:f.exe
Microsoft (R) Incremental Linker Version 14.28.29337.0
Copyright (C) Microsoft Corporation. All rights reserved.C:\Temp>f.exe
s: Hello; expected is Hello
len: 5 ; expected is 5C:\Temp>