【问题标题】:Fortran functions and return valuesFortran 函数和返回值
【发布时间】:2010-11-22 23:02:51
【问题描述】:

如何在 Fortran 中编写一个同时接受输入和输出作为参数的函数?例如:

fun(integer input,integer output)

我想利用输出值。我尝试过类似的方法,但输出变量没有保存该值。

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

【问题讨论】:

  • 你能粘贴你的fortran和c签名吗

标签: fortran


【解决方案1】:

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

sin_of_x = sin(x)

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

【讨论】:

    【解决方案2】:

    一个例子。如果你想要一个返回 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
    

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

    【讨论】:

    • 那么 Fortran 函数和子程序之间唯一的实际区别是子程序不返回值吗?
    • @naught101:不,还有其他的不同,但是我有两年的锈迹,所以我不记得细节了。
    猜你喜欢
    • 2016-10-23
    • 2012-08-02
    • 1970-01-01
    • 2020-06-02
    • 2014-07-24
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多