tags:

views:

245

answers:

2

Hi,

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

fun(integer input,integer output)

I want to make use of the output value. I have tried something like this but the output variable is not holding the value.

Specifically, I am calling a C function from Fortran which takes input and output as parameters. I am able to pass input values successfully, but the output variable is not acquiring a value.

+2  A: 

Ravi

Your fun() is what Fortran programmers, such as me, call a SUBROUTINE (yes, we shout our keywords in Fortran-town too). A FUNCTION is a value-returning thing like this:

sin_of_x = sin(x)

So your first decision is which approach your Fortran code will take. You probably want to use SUBROUTINE. Then sort out the INTENT of your arguments.

Regards

Mark

High Performance Mark
A: 

An 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 are calling a C routine, then the signature makes use of 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 gets messy.

Stefano Borini