3

如何在 Fortran 中编写一个将输入和输出都作为参数的函数?例如:

fun(integer input,integer output)

我想利用输出值。我已经尝试过这样的事情,但输出变量没有保存该值。

具体来说,我从 Fortran 调用一个 C 函数,它将输入和输出作为参数。我能够成功传递输入值,但输出变量没有获取值。

4

2 回答 2

5

在 Fortran 中,您fun()的程序称为子程序。函数是一个像这样返回值的东西:

sin_of_x = sin(x)

因此,您的第一个决定是您的 Fortran 代码将采用哪种方法。您可能想要使用子例程。然后理清你的论点的意图。

于 2009-08-26T11:05:36.517 回答
4

一个例子。如果你想要一个返回 void 的函数,你应该使用一个子例程。

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 

如果您正在调用 C 例程,则签名使用引用。

$ 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

如果你使用字符串,事情就会变得一团糟。

于 2009-08-26T11:09:45.167 回答