JimBamFeng
JimBamFeng

Reputation: 749

Passing pointer from C to fortran Subroutine

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)

Upvotes: 2

Views: 1817

Answers (2)

M. S. B.
M. S. B.

Reputation: 29401

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

Upvotes: 6

paulsm4
paulsm4

Reputation: 121869

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:

Upvotes: 1

Related Questions