Fortran Functions and Return Values

How can I write a function in Fortran that takes both input and output as arguments? For example:

fun(integer input,integer output)

      

I want to use the output value. I've tried something like this, but the output variable doesn't hold the value.

Specifically, I am calling a C function from Fortran that takes input and outputs it as parameters. I can successfully pass the input values, but the output variable is not getting a value.

+2


source to share


2 answers


Your pleasure () is what Fortran programmers like me call SUBROUTINE (yes we shout our keywords in Fortran city). A FUNCTION is a value-returning thing like this:

sin_of_x = sin(x)

      



So your first solution is the approach of your Fortran code. You probably want to use SUBROUTINE. Then select the INTENT of your arguments.

+5


source


Example. if you want a function that returns void you should use a subroutine instead.

function foo(input, output)
    implicit none
    integer :: foo
    integer, intent(in) :: input
    integer, intent(out) :: output

    output = input + 3
    foo = 0
end function

program test
    implicit none
    integer :: a, b, c, foo

    b = 5
    a = foo(b, c)

    print *,a,b, c

end program 

      

If you call a C routine, then the signature uses references.



$ cat test.f90 
program test
    implicit none
    integer :: a, b, c, foo

    b = 5
    a = foo(b, c)

    print *,a,b, c

end program 

$ cat foo.c 
#include <stdio.h>
int foo_(int *input, int *output) {
    printf("I'm a C routine\n"); 
    *output = 3 + *input;

    return 0;
}


$ g95 -c test.f90 
$ gcc -c foo.c 
$ g95 test.o foo.o 
$ ./a.out 
I'm a C routine
 0 5 8

      

if you use strings things get messy.

+3


source







All Articles