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.