A lot of C libraries use filepointers (FILE *) for their input and output routines.
When writing C wrappers for these libraries, it is possible to use the type c_ptr for
the filepointer object and create interfaces to fopen and fclose.
In principle, this works fine. However, the consequence is that filehandling has to be done
in the way it is done in C, not the way it is usually done in fortran (open, close, integer value
for the file unit.) and there may be two different way to handle files in the same program or library.
See below, as an example, a program that uses a Fortran binding to the graphics library GDlib I am currently working on:
So it would be nice if there exists a (portable) way to link Fortran file units to File pointers an vice versa.
program test_fortran_gd
use iso_c_binding, only: c_ptr, c_int, c_null_char
use fortran_libgd
implicit none
type(c_ptr) :: im
! file pointer
type (c_ptr) :: pngout,
integer(c_int):: black
integer(c_int):: closestatus
im = gdImageCreate(64_c_int, 64_c_int)
black = gdImageColorAllocate(im, 0_c_int, 0_c_int, 0_c_int)
! gd_fopen ist just a wrapper for C's fopen
pngout = gd_fopen("test_black.png"//c_null_char, "wb"//c_null_char)
call gdImagePng(im, pngout)
! close file
closestatus = gd_fclose(pngout)
call gdImageDestroy(im);
end program test_fortran_gd
The Sun/Oracle Compiler has (had ?) the function getfilep
available, that took the unit number of a file as an argument and returned the address of the file pointer. However, this seem to be a proprietary vendor extension (and pre-2003 Fortran).
So I would be interested, whether there are more portable approaches.