Using the same procedure name in Fortran as interfaced C function

This is my first attempt to use modern Fortran to C interfacing. The last time I did something similar was (many years ago) by manually adding underscores to F77 procedure names in wrappers written in C.

My code (just a beginning of a long way) to use a C library from Fortran is:

module phot_db
  use, intrinsic :: iso_c_binding
contains
  integer function opendb(fld, flt) result(res)
    character(*), intent(in) :: fld, flt
    interface
       function opendb_w(fld,flt) bind(c,name="opendb")
         import :: c_int, c_char
         integer(c_int) :: opendb_w
         character(c_char),dimension(*) :: fld, flt
       end function opendb_w
    end interface
    res = opendb_w(trim(fld)//c_null_char, trim(flt)//c_null_char)
  end function opendb
end module phot_db

As you can see, I tried to give Fortran wrapper the very same name as that of the corresponding C function, using name clause in bind attribute and giving the interface entry slightly modified name (opendb_w) to avoid a recursion loop.
And it works, at least in gfortran. My question is whether this is legal and guaranteed to work in any processor.

Another question is whether one should provide explicit conversion between C-interoperable and standard Fortran types, e.g. c_int and integer. Surely I would like to avoid using c_* types in Fortran programs, outside the interface module.

That conforms and any conforming processor shall process the instructions.

Re: “Another question is whether one should provide explicit conversion between C-interoperable and standard Fortran types,” you knew the answer to this second question already when you mentioned “in any processor” in your first question! You know the default integer in any processor may or may not be the same kind as c_int, so you can proceed accordingly.

1 Like

Thanks @FortranFan for reassuring response.

I had doubts because my (maybe oversimplified) guess was that the only way to make the linker work fine on such a mixed program would be to internally call same-named procedures by slightly different name in Fortran and C. As one can easily see converting F90 code to assembly, both gfortran and ifort do indeed call the (Fortran) function opendb as (assembly) call opendb_ (as it used to be 30 years ago), contrary to the C compiler which does not add anything to the function name. Still, I was not sure how Fortran Standard can assure it is universal.