Passing pointer from C to fortran Subroutine

不羁岁月 提交于 2019-12-06 10:43:24

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

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!