2

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)

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.