问题
I am trying to call a fortran subroutine from C, can I allocate in C and pass the pointer to Fortran safely? The array in the subroutine is an automatic array (x(nmax)).
(I am allocating the x and then passing it to the fortran)
回答1:
Yes. Modern Fortran guarantees that Fortran routines can be called from C and vice-a-versa. This is done via the Fortran ISO_C_BINDING. This is part of Fortran 2003 and was widely available as an extension to Fortran 95 compilers. There is documentation in the gfortran manual (Chapters "Mixed-Language Programming" and "Intrinsic Modules".) As a language feature, this documentation is more useful than just for the gfortran compiler. There are also examples here on stackover that can be found via the fortran-iso-c-binding tag.
Simple code example:
#include <stdio.h>
#include <stdlib.h>
void F_sub ( float * array_ptr );
int main ( void ) {
float * array_ptr;
array_ptr = malloc (8);
F_sub (array_ptr);
printf ( "Values are: %f %f\n", array_ptr [0], array_ptr [1] );
return 0;
}
and
subroutine F_sub ( array ) bind (C, name="F_sub")
use, intrinsic :: iso_c_binding
implicit none
real (c_float), dimension (2), intent (out) :: array
array = [ 2.5_c_float, 4.4_c_float ]
end subroutine F_sub
回答2:
In general, "yes": you can pass C arrays to FORTRAN, and vice versa. Especially if both compilers are from the same vendor (e.g. call gcc functions from a g77 program).
Here are two good links:
http://www.yolinux.com/TUTORIALS/LinuxTutorialMixingFortranAndC.html
http://arnholm.org/software/cppf77/cppf77.htm
来源:https://stackoverflow.com/questions/17538937/passing-pointer-from-c-to-fortran-subroutine