Converting a variable length c-string to Fortran string in Visual Studio

Solution 1:

It is unclear in the question how the C code would use the Fortran string?

If the string comes from a C function:

const char *getcstr(void)
{
    return "Hello!";
}

here is the complete Fortran program that calls the C function, turns the result into a Fortran string, then prints:

implicit none

interface
    function getcstr() bind(c, name="getcstr")
        use, intrinsic :: iso_c_binding
        type(c_ptr) getcstr
    end
end interface

print *, cstr2f(getcstr())

contains
    function cstr2f(s)
        use, intrinsic :: iso_c_binding
        interface
            pure function strlen(s) bind(c, name="strlen")
                use, intrinsic :: iso_c_binding
                type(c_ptr), intent(in), value :: s
                integer(c_size_t) strlen
            end
        end interface
        type(c_ptr) s
        character(kind=c_char, len=strlen(s)), pointer :: cstr2f

        call c_f_pointer(s, cstr2f)
    end
end